Skip to content

Instantly share code, notes, and snippets.

@lmcgartland
Created December 21, 2017 18:13
Show Gist options
  • Save lmcgartland/29de1580e6f723408e2dc2e42efaa4ec to your computer and use it in GitHub Desktop.
Save lmcgartland/29de1580e6f723408e2dc2e42efaa4ec to your computer and use it in GitHub Desktop.
// Authentication Link Example from https://www.apollographql.com/docs/react/recipes/authentication.html#Header
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}` : null,
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment