Access Response Headers in Apollo Client
How to access response headers in Apollo client. This can be useful for storing the authorization header being sent from the server.

I have a server that sends back a new JWT with each response. There's a simple example on the Apollo docs of setting request headers, but no mention of accessing response headers.
The main reason to do this, was accessing the Authorization
header so that I could update a JWT token that I stored on the client side.
Adding the Link
Go into your Apollo Client code. You need to make a new link:
import { ApolloLink } from '@apollo/client'
const afterwareLink = new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
const context = operation.getContext()
const authHeader = context.response.headers.get('Authorization')
localStorage.setItem('token', authHeader)
return response
})
})
The code is pretty simple! At the time of writing I couldn't find any examples of afterware in the docs. You call forward on the operation so that it is ran, and then mapping over it calls your code with the response.
Now we add the afterware link to our client:
import …
Keep reading with a 7-day free trial
Subscribe to zach.codes to keep reading this post and get 7 days of free access to the full post archives.