Disable apollo client metric headers
Thu 25 Aug 2022
An apollographql-client-version was constantly added to my graphql requests towards the github graphql endpoint.
I solved it by setting clientAwareness to false. Without this the github api request was denied by CORS. Browser simply dropped the request with an error:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.github.com/graphql. (Reason: header ‘apollographql-client-version’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response)."
Example code for the solution:
const authMiddleware = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('token');
operation.setContext(() => {
return {
/* 👇 This is needed in order to disable the metrics apollo client headers */
clientAwareness: false,
headers: {
Authorization: `bearer ${token}`,
},
};
});
return forward(operation);
});
// And then providing it into your module providers like so:
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: (httpLink: HttpLink) => {
return new ApolloClient({
cache: new InMemoryCache(),
link: concat(
authMiddleware,
httpLink.create({ uri: environment.apiUrl })
),
});
},
deps: [HttpLink],
},
],This finally removed my metric headers from the requests 😉