1

How can I update the token during runtime in an instantiated apollo-client instance?

const middleware = new ApolloLink((operation, forward) => {
    operation.setContext({
        headers: new HttpHeaders().set('Authorization', 'Bearer ' + token || null)});
        return forward(operation);
    });


apollo.createNamed(id, {
    link: from([logoutLink, middleware, http]),
    cache: new InMemoryCache(),
});

The apollo instance has a link property, which itself is a ApolloLink instance, which has the concat method.

apollo.getclient().link.concat()

But calling that concat returns a new ApolloLink instance. Is there a way to update the client instance with this new ApolloLink?

Han Che
  • 8,239
  • 19
  • 70
  • 116

1 Answers1

2

You don't need to create a new ApolloLink -- you pass a function to ApolloLink's constructor that's ran each time a request is made, so just handle that logic inside the function:

const middleware = new ApolloLink((operation, forward) => {
  const headers = new HttpHeaders()
  const token = getTokenFromWherever()
  headers.set('Authorization', 'Bearer ' + token)
  operation.setContext({ header })
})
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 1
    I am applying a use case where in my app some graphql queries not need to send authorization headers. I have set context, how do I remove authorization header when making those specific requests grapql – Wikki Nov 13 '21 at 20:15