Created
December 21, 2017 18:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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