adamsoffer / next-apollo

React higher-order component for integrating Apollo Client with Next.js
MIT License
482 stars 64 forks source link

How to Implement Token Refresh? (cookies) #89

Closed joncursi closed 3 years ago

joncursi commented 3 years ago

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?

joncursi commented 3 years ago

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,
  });