Search code examples
apolloapollo-clientapollo-server

Unable to set authorization header using Apollo's setContext()


So I'm trying to pass an authorization header to Apollo according to the docs on their site.

https://www.apollographql.com/docs/react/networking/authentication/?fbclid=IwAR17YAJ0VA5G8InmAJ_PxcukXKNQxFLFI8aeT4oB7wYE3DjWNaB_F67__zs

However, when I try to log request.headers on my server I don't see the authorization property on there. Next I checked whether or not the function setContext() was being run at all by putting a console.log() within it and found that it didn't run.

const httpLink = new HttpLink({ uri: 'http://localhost:4000' });

const authLink = setContext((request, { headers }) => {
  const token = localStorage.getItem('library-user-token')
  console.log(token)    //doesn't log at all
  return ({
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  })
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

Solution

  • I have almost identical code in my project and it works. Are you passing the client to your ApolloProvider?