adamsoffer/next-apollo

How to Implement Token Refresh? (cookies)

Closed this issue · 1 comments

My apollo client setup requires that an authorization header must be set with a bearer token on all GraphQL requests. The application pulls this token from the user's cookies, provided they have logged in previously. The cookie / token expires after 1 hour, but before expiration, I have code in place to "refresh" the cookie / token.

The problem, though, is that Apollo Client requests are still firing with the old token, as they do not detect the cookie change since it's outside of the scope of React. Is there a way to tell next-apollo to "dynamically" attach the bearer token to each render request, so that Apollo Client is always using the latest token when sending requests?

Solved using a context link to dynamically set the Auth header:

import { setContext } from '@apollo/client/link/context';

  const authLink = setContext(
    (_, { headers }): Record<string, any> => {
      const token = fetchTokenDynamically(cookie);

      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : '',
        },
      };
    },
  );

  link = ApolloLink.from([authLink, ..., ...]);

  return new ApolloClient({
    cache: new InMemoryCache({}),
    link,
  });