Passing JWT Token into Apollo Context with NextJs

Viewed 549

I am having some trouble passing my jwt token into the context of my Apollo server using NextJs. Before when I have been using React and Express, I was able to pass the token in the headers like this:

const client = new ApolloClient({
  request: (operation) => {
    const token = localStorage.getItem('id_token');
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : '',
      },
    });
  },
  uri: '/graphql',
});

However, now I seem to be having some trouble setting the token in the header because localStorage is not defined at the time that Next is running this code. I have found tutorials for setting up JWT with Next, Next with Apollo, and Apollo with JWT. Unfortunately I haven't been able to find very much help for the specific combination of Next, Apollo, and JWT and setting the authorization header.

Any suggestions?

1 Answers

For anyone else that runs into this issue, I have found a working solution.

Solution comes from here: https://lyonwj.com/blog/grandstack-podcast-app-next-js-graphql-authentication

Rather than using localStorage, the token can be stored in the app state through useContext. The disadvantage of this is that the "login" only exists while you are on the page.

It is probably possible to workaround this by saving a copy of the latest token to the db and looking for it when you revisit the site. If it isn't expired, you're logged in. Otherwise, prompt user to log in.

Related