NextAuth.js signout if Apollo GraphQL token is invalid or it has expired

Viewed 2197

What would it be the best way to clear the NextAuth.js session when trying to hit the backend (Apollo GraphQL) and it returns a 401 because the token has expired or is invalid?

I thought about an errorLink and signout, but as far as I know signout cannot be used server side at getServerSideProps, but only client-side.

What is the recommended way to do so? Is there any other way to implement a middleware to take care of that scenario?

Thanks

2 Answers

It depends on which version of Apollo you are using, but assuming you are using Apollo 3.0 <= you can create a setcontext for your requests.

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

const authLink = setContext((_, { headers }) => {
  const token = session?.accessToken ? session.accessToken : ""
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

function createApolloClient(session) {
  return new ApolloClient({
    cache: new InMemoryCache(),
    ssrMode: typeof window === 'undefined',
    link: from([
      authLink,
      errorLink,
      createUploadLink({
        uri: GRAPHQL_URI,
        credentials: 'same-origin'
      }),
    ]),
  });
}

Since signOut() rerenders your app you can check the context to see whether it has a valid token on the request from your server. Haven't tested this, but in theory this is how I might implement it.

Related