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()
});
That function inside of
setContextwill 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
contextoption to youruseQuerycalls, so you can use that, too, to set custom headers for an individual request.