After reading many articles on how to handle re-authentication for Apollo React, I have determined that I need to write my own logic to handle checking an expired JWT, refreshing the token, and then proceeding with an operation. I don't want to redirect to any kind of login page, from an error or wait until an error happens to refresh my token.
So I've followed the Apollo docs a bit to append a token to the header of every request. This works just fine:
const authLink = new ApolloLink((operation, forward) => {
operation.setContext(({ headers = {} }) => {
const token = localStorage.getItem('token');
// TODO: Check if token is expired. If so, fetch a new one from GraphQL server and THEN
// move forward with operation
// If token exists, add to headers
if (token) {
headers = { ...headers,authorization: token ? `Bearer ${token}` : "", };
}
return { headers };
});
return forward(operation);
});
const httpTopicsServiceLink = createHttpLink({
uri: 'http://localhost:4000/topics',
});
export const TopicsClient = new ApolloClient({
link: authLink.concat(httpTopicsServiceLink),
cache: new InMemoryCache(),
});
However, inside of authLink function, I want check if the token is expired to be able to send a GraphQL mutation to a server to refresh my token and THEN forward my operation. Since I've been doing all my GraphQL queries and mutations inside of the Apollo <Query /> and <Mutation /> components, I'm not sure how to make an isolated request to a GraphQL server to accomplish this kind of functionality. What can I do?