Ad

React & Apollo, How To Set Authorization Header When User Logs In?

- 1 answer

Assume we create a client like this initially

const client = new ApolloClient({
  uri:'https://api.com/graphql'
})

Initially this api has some mutations like signIn and signUp exposed, that don't require authentication.

Somewhere down the line user signs in and receives an auth token. This token now needs to be set on our apollo client as a header i.e.

headers: {
   Authorization: `Bearer ${token}`
}

Is it possible to somehow update client "on the fly" to apply this header in order for future api requests to use it?

Ad

Answer

According to the documentation you can do this :

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

UPDATE

You can update your token using 'apollo-boost'

Note that the above example is using ApolloClient from the apollo-client package. Headers can still be modified using ApolloClient from the apollo-boost package, but since apollo-boost doesn't allow the HttpLink instance it uses to be modified, headers have to be passed in as a config parameter:

import ApolloClient from 'apollo-boost'

const client = new ApolloClient({
  request: (operation) => {
    const token = localStorage.getItem('token')
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : ''
      }
    })
  }
}) 
Ad
source: stackoverflow.com
Ad