Ad

Update ApolloClient Headers After It Was Initialised

- 1 answer

My app is wrapped with <Apollo /> component that essentially initialises the client.

const client = new ApolloClient({
  link: new HttpLink({
    // ...
  }),
  cache: new InMemoryCache({
    // ..
  }),
});

Further down the road users can make certain action that requires me to set few new headers to apollo client that were not there before. I initially thought to use react context for this to pass set new headers and consume them inside <Apollo /> but am not sure if this is the right way to go about it.

After looking through the docs, it seems that apollo headers can be only set when it is initialised?

Ad

Answer

Rather than passing the headers directly to your Apollo client instance, you normally want to utilize apollo-link-context. You can store the actual header values in memory, LocalStorage or whatever makes sense for your app. Then use the link to inject them into each request before it's sent:

const headerLink = setContext((request, previousContext) => ({
  headers: {
    // Make sure you include any existing headers!
    ...previousContext.headers,
    authorization: localStorage.getItem('authHeader')
  },
}));

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

setContext can be asynchronous. The function you pass it should return either an object with whatever context fields you want to change, or a Promise that will resolve to one:

const headerLink = setContext(async (request, previousContext) => {
  const authorization = await someAsyncCall()
  return {
    headers: {
      ...previousContext.headers,
      authorization,
    },
  }
});

You can check out the docs for additional examples.

Ad
source: stackoverflow.com
Ad