'Update ApolloClient headers after it was initialised

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?



Solution 1:[1]

To expand on Daniel Rearden's answer, if you want to add headers just for a specific query/mutation and not all of the subsequent queries:

Initialise Apollo:

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

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

And then simply add the context to the desired query/mutation itself:

const {loading, data, error} = useQuery(QUERY_DEF, { 
    context:  {
        headers: {
            "HeaderKey": "HeaderValue"
        }
    }
});

Solution 2:[2]

Daniel Rearden is right. However, with Apollo 3 there're some minor changes that I've found not well systematized in the docs yet. So maybe it will help as well.

import React from 'react';
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

function App() {

  const link = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URI });

  const setAuthorizationLink = setContext((request, previousContext) => ({
    headers: {
      ...previousContext.headers,
      authorization: `Bearer ${ localStorage.getItem('auth_token') }`
    }
  }));

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

  return (
    <ApolloProvider client={client}>
      ...
    </ApolloProvider>
  );
}

export default App;

Migrating to Apollo Client 3.0 (docs)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Syed Waqas
Solution 2 sketchnotes