reactjsreact-apolloapollo-client

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...


Solution

  • I used the setContext method as described there : https://www.apollographql.com/docs/react/networking/authentication#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,
    });