React & Apollo, How To Set Authorization Header When User Logs In?
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?
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}` : ''
}
})
}
})
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?