Set Context with Apollo Client

4 Oct 2022

Quite often there will be times you'll want to update your Apollo Client based on the behaviour of users in your app, or authentication headers for logged-in users.

In this video we'll explore adding a custom Apollo Link that updates our request headers using the value from a custom context provider.

We want to pass a custom header with our HTTP request whereby the value is saved in context. The user can change the value at any time, so we'll need to fetch the value on the fly. We can do this with creating a "link chain".

We must terminate our chain with the HttpLink:

const httpLink = new HttpLink({
  uri: "https://api.cartql.com",
});

We can then chain our custom currencyMiddlware and httpLink links using from:

return new ApolloClient({
  link: from([currencyMiddleware, httpLink]),
  cache: new InMemoryCache(),
});

The full <MyApolloProvider /> component looks like this:

const MyApolloProvider = ({ children }: PropsWithChildren) => {
  const { currency } = useCurrencyContext();

  const client = useMemo(() => {
    const currencyMiddleware = setContext((operation, { headers }) => {
      return {
        headers: {
          ...headers,
          "cartql-currency": currency,
        },
      };
    });

    return new ApolloClient({
      link: from([currencyMiddleware, httpLink]),
      cache: new InMemoryCache(),
    });
  }, [currency]);

  return <ApolloProvider client={client}>{children}</ApolloProvider>;
};