Session in webSocket subscriptions
See original GitHub issueI’m using Apollo Server 2 and Express.js vanilla (with apollo-server-express
).
Everything works good also with Subscriptions except the Express session mechanism.
The problem:
I’m using cookie-session (https://github.com/expressjs/cookie-session, but I think this is the same for express-session middleware) and when my browser start a new connection with my server the ApolloServer onConnect
hook doesn’t have the req
attribute and neither req.session
and so on…
What I can do is to parse the cookies from webSocket.upgradeReq.headers.cookie
in onConnect
lifecycle hook, but it seems to me very hacky.
The code:
const { ApolloServer } = require('apollo-server-express')
const typeDefs = require('../src/graphql/types')
const resolvers = require('../src/graphql/resolvers')
const models = require('../src/models')
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: ({ req, connection }) => {
// connection exists only on webSocket connection
if (connection) {
return {
currentUser: connection.context.currentUser // <-- I NEED THIS!
}
}
// if not a (webSocket) connection it is a "default" HTTP call
return {
models,
currentUser: { id: req.user.id }
}
},
subscriptions: {
onConnect: (connectionParams, webSocket) => {
// "connectionParams" is from the client but I cannot use it because cookies are HTTP-Only
// I can retrieve cookies from here: "webSocket.upgradeReq.headers.cookie" but then I need to parse them which seems a bit hacky to me
// return { currentUser: req.user.id } // <-- I NEED THIS (req.user.id doesn't exists)!
}
}
})
module.exports = apolloServer
I can’t find anything on Apollo Server Docs site (for other topics very well documented! Just this: https://www.apollographql.com/docs/apollo-server/features/subscriptions.html#Context-with-Subscriptions).
Where am I doing wrong?
StackOverflow question: https://stackoverflow.com/questions/52280481/graphql-subscription-websocket-nodejs-express-session-with-apollo-server-2
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:9 (1 by maintainers)
Top GitHub Comments
The way i found to deal with this using express session is doing something like this:
Any updates on this?