Set Authorization Header with Apollo Client
A GraphQL API often requires us to provide an authorization header to authenticate the request. How can we provide this authorization header using the popular Apollo Client library?
It turns our Apollo already provides us with the apollo-link module. apollo-link is a composable network layer that we can use to configure the HTTP request. With apollo-link, we can create chainable middlewares that will construct our final HTTP request.
Suppose our initial code to instantiate an Apollo Client look like this:
Let’s say we store our authorization token on a local storage. To set the authorization header, we need to create an instance of ApolloLink
and combine it with the current HttpLink
instance.
The ApolloLink
accepts exacly one parameter: the “Request Handler” function. This request handler function accepts two parameters: operation
and forward
. We can use the operation.setContext
method to set any HTTP headers. We then call the given forward
function to execute the next middleware in chain.
Originally published at risanb.com on April 14, 2018.