I’d like to set custom headers for individual requests, e.g. not when initialising ApolloClient.
I am running a query like this:
client.query({ query: /* some graphql query */});
I have tried like this:
client.query({
query: /* some graphql query */,
contenxt: {
headers: {
"SomeCustomHeader": 123
}
}
});
But that did not work. Is there another way to do it, on the fly?
@apolloinspace May I ask if you ever found a solution to this? I"m currently having the same trouble, with custom headers not being sent upstream to the GQL end-point?
Also throwing out the question to the rest of the community: I’m noticing the same thing happening, using authentication via the ApolloLink()
approach from the above link about Advanced HTTP Networking.
As far as I can see, only the Authorization
header gets sent upwards; my custom headers (set from the ApolloLink
in the JS client) aren’t being bound to the onwards query, I think. It’s hard to tell as I don’t have access to the backend’s logging.
Now, if I use a custom dataSource
, and add the headers to the request there (then call the request via a custom set of resolvers, then it works fine & the headers are apparently set). However this adds maintenance and complexity to the codebase as we’re using microservices and a lot of stitched schemas.
This is very confusing,
I created a middleware on my client in order to pass additional headers to my GraphQL instance.
// link to pass current language on every query
const middleware = new ApolloLink((operation, forward) => {
const headers = {
// send language requested in headers
language: "en",
// another header
clientType: "BACKEND",
};
// add the authorization to the headers
operation.setContext({
headers,
});
return forward(operation);
});
// and then in my client (i use Batch but should work with the normal one)
const httpLink = new BatchHttpLink({
uri: "",
});
const client = new ApolloClient({
link: new ApolloLink.from([middleware, httpLink]),
cache: new InMemoryCache(),
});
Actual example is here: Advanced HTTP networking - Apollo GraphQL Docs
please check spelling for context .
It worked fine for me