Using headers with Apollo Datasources

Some of our services at Wehkamp require some headers to be set, otherwise they return an error. When calling these services directly from the website, this is not a problem. The headers are set by the site gateway that all requests go through.

However, when you do a GraphQL call, the call from the browser that goes through the gateway, goes to your /graphql endpoint. Then, in the resolver the DataSource is called. The DataSource then creates a new request to the service. As this request doesn’t go through the site gateway, it doesn’t get the headers and the request fails.

It’s not possible to use the willSendRequest method on the DataSource to solve this, because you don’t have access to the original request there. And it’s also not possible to add it to the context when instantiating the DataSource, because the values can be different for each request.

However, the solution for this is simple: get the headers from the request to /graphql and pass them to the DataSource request. The request in the resolver context is the request from the browser to /graphql . We extract the headers we need by using a filterHeaders function to reduce the incoming headers to an object containing only the headers we need. Keep in mind that the headers on the incoming request are lowercase, so in the filter method we explicitly convert the list of headers to lowercase.

Once we have an object with just the headers we need, we pass that into the DataSource method as part of an options object. The next step is not documented in the Apollo docs, but the http verb methods provided by the Apollo DataSource have three parameters: url, body and options. And that last parameter can contain a headers property to attach to the outgoing request.

And that solves the whole problem!

Thank you for taking the time to reading this story! You can follow me on Twitter @ronderksen and feel free to tweet me anything!

Also, I work at Wehkamp one of the biggest e-commerce companies of the Netherlands. We do have a Tech blog, check it out and subscribe if you want to read more stories like this one. Or look at our job offers if you are looking for a great job!