Skip to content

Instantly share code, notes, and snippets.

@cowlicks
Last active May 16, 2020 03:19
Show Gist options
  • Save cowlicks/71e766164647f224bf15f086ea34fa52 to your computer and use it in GitHub Desktop.
Save cowlicks/71e766164647f224bf15f086ea34fa52 to your computer and use it in GitHub Desktop.
Dynamic auth tokens for Websockets with Graphql Subscriptions
const subscriptionMiddleware = {
applyMiddleware: function(options, next) {
// Get the current context
const context = options.getContext().graphqlContext;
// set it on the `options` which will be passed to the websocket with Apollo
// Server it becomes: `ApolloServer({contetx: ({payload}) => (returns options)
options.authorization = context.authorization;
next()
},
};
const server = new ApolloServer({
context: ({connection, payload, req}) => {
// whatever you return here can be accessed from the middleware of the SubscriptionMiddleware with
// applyMiddleware: (options, next) => options.getContext()
return {authorization: payload.authorization};
},
});
const link = new WebSocketLink({
uri: WS_URL,
webSocketImpl: WebSocket,
options: {
reconnect: true,
}
});
link.subscriptionClient.use([subscriptionMiddleware]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment