Custom and dynamic headers for different queries React.js Apollo

41 Views Asked by At

I'm inquiring about a way to set custom headers for different queries using Apollo. With the code below, found on Apollo Docs, a header is set for all HTTP requests using that client variable. Is there a way to globally declare the variable authLink or another variable so it can be changed in different files and functions? Or is there a better way to set headers? Any help would be greatly appreciated. Thank you.

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

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()
});
1

There are 1 best solutions below

0
phry On

That function inside of setContext will be executed every time you have an outgoing request, so you could have any kind of logic in there, including logic that would read from global variables that you set elsewhere in your code.

That said, you can also pass a context option to your useQuery calls, so you can use that, too, to set custom headers for an individual request.