Skip to content

Instantly share code, notes, and snippets.

@gotexis
Forked from clarencenpy/apollo-boost-reauth.js
Created March 19, 2019 13:16
Show Gist options
  • Save gotexis/8731def8b1e66826d7bd4f757f8d733c to your computer and use it in GitHub Desktop.
Save gotexis/8731def8b1e66826d7bd4f757f8d733c to your computer and use it in GitHub Desktop.
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: '<your graphql endpoint>',
// Apollo Boost allows you to specify a custom error link for your client
onError: ({ graphQLErrors, networkError, operation, forward }) => {
if (graphQLErrors) {
for (let err of graphQLErrors) {
// handle errors differently based on its error code
switch (err.extensions.code) {
case 'UNAUTHENTICATED':
// old token has expired throwing AuthenticationError,
// one way to handle is to obtain a new token and
// add it to the operation context
const headers = operation.getContext().headers
operation.setContext({
headers: {
...headers,
authorization: getNewToken(),
},
});
// Now, pass the modified operation to the next link
// in the chain. This effectively intercepts the old
// failed request, and retries it with a new token
return forward(operation);
// handle other errors
case 'ANOTHER_ERROR_CODE':
// ...
}
}
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment