Ad
Change Apollo Client Options For Jwt Token
I want to set up a token in my apollo client when the user logs in.
This is my index.js:
const client = new ApolloClient({
ssrMode: SERVER_MODE,
cache: new InMemoryCache().restore(cache),
link: createUploadLink({
uri: process.env.REACT_APP_API_URL,
fetch: SERVER_MODE ? global.fetch : NetworkService.customFetch,
headers: {
Authorization: 'Bearer ' + window.localStorage.access_token,
}
}),
defaultOptions: NetworkService.defaultOptions,
});
ReactDOM.render(
<ApolloProvider client={client}>
<Router>
<App client={client}/>
</Router>
</ApolloProvider>,
document.getElementById('root')
);
The thing is, when the app starts there is no token, so the client is initialized with token: null.
When the user logs in, I set the token but I somehow need to refresh my application to take in account the token.
The login function just saves the token in the localStorage after a successful login api call.
How should I approach this? Right now, I'm doing a full page reload after login to bypass this problem...
Ad
Answer
I used the setContext
method as described there : http://dev.apollodata.com/react/auth.html#Header and it works fine !
static authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem('access_token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
};
});
...
new ApolloClient({
ssrMode: SERVER_MODE,
cache: new InMemoryCache().restore(cache),
link: ApolloLink.from([
NetworkService.authLink,
NetworkService.errorLink,
NetworkService.uploadLink
]),
defaultOptions: NetworkService.defaultOptions,
});
Ad
source: stackoverflow.com
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?
Ad