I'm using Apollo Server 2 (but this problem is not only with Apollo) 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!).
Where am I doing wrong?