Skip to content

Instantly share code, notes, and snippets.

@gengns
Created October 13, 2021 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gengns/ed1a5c67ca405401a1d9517f8a207b14 to your computer and use it in GitHub Desktop.
Save gengns/ed1a5c67ca405401a1d9517f8a207b14 to your computer and use it in GitHub Desktop.
Set WebSockets and HTTP authorization with Apollo after getting your token
/**
apollo.js
Set WebSockets and HTTP authorization with Apollo Client after getting your token in your login.
I'm using a Svelte's store here to get the token but you can use Vanilla with sessionStorage or whatever you like
*/
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
import { WebSocketLink } from 'apollo-link-ws'
import { split } from 'apollo-link'
import { getMainDefinition } from 'apollo-utilities'
import { setContext } from 'apollo-link-context'
import { token } from 'store'
import { get } from 'svelte/store'
// HTTP ************************************************************************
// Next function will get called every time our client tries to communicate
const authLink = setContext((_, { headers }) => {
// Only add if token
if (get(token))
return {
headers: {
...headers,
authorization: `Bearer ${get(token)}`
}
}
})
const httpLink = new HttpLink({
uri: 'https://your_endpoint.com/v1/graphql'
})
// WEBSOCKET *******************************************************************
// Adding auth over WebSocketLink is different than HttpLink
const wsLink = new WebSocketLink({
uri: 'wss://your_endpoint/v1/graphql',
options: {
lazy: true, // lazy allow get latest token
reconnect: true,
connectionParams: () => ({
headers: {
authorization: `Bearer ${get(token)}`
}
})
}
})
// CHOOSE BETWEEN HTTP AND WEBSOCKET *******************************************
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query)
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
)
},
wsLink,
authLink.concat(httpLink)
)
// APOLLO CLIENT ***************************************************************
export default new ApolloClient({
link,
cache: new InMemoryCache({
addTypename: false // this affects cache performance
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment