-
Notifications
You must be signed in to change notification settings - Fork 340
Session in webSocket subscriptions #466
Comments
These two are probably relevant / helpful for fixing this in the apollo server itself:
|
The socket appears to already be available as part of the connection context, I'll see if it's possible to access the session cookie from there. |
To get session contents expressjs/cookie-session#117 (comment) |
I've got it to work on a sideproject of mine: https://github.com/niklaskorz/nkchat/ |
I solved this problem in the const options = {
cors: { credentials: true, origin },
port: PORT,
subscriptions: {
onConnect: async (connectionParams, webSocket) => {
try {
const promise = new Promise((resolve, reject) => {
session(webSocket.upgradeReq, {}, () => {
resolve(webSocket.upgradeReq.session.passport);
});
});
const user = await promise;
return user;
} catch (error) {
console.log('error', error);
}
},
},
}; Next, when you initialize the server, you can get the const server = new GraphQLServer({
typeDefs,
resolvers,
context: ({ request, connection }) => {
let user = request ? request.user : null;
if (connection) {
if (connection.context.user) user = connection.context.user;
}
return { user, request, pubsub };
},
}); An example can be found here https://github.com/bakhaa/pw/blob/master/api/app.js. |
I am just using apollo-express-sever and session inside of context.
But I get this error when I am executing subscription in playground. If I remove the context including session, that error disappears. Why is it happening? |
@Apollo725 |
We use this something like this: subscriptions: {
keepAlive: 10000,
onConnect: (_params, _ws, ctx) => {
const promise = new Promise((resolve, reject) => {
const req = ctx.request as express.Request;
const res = ({} as any) as express.Response;
sessionHandler(req, res, _ => {
const userId = req.session && req.session.userId;
return resolve({ userId });
});
});
return promise;
},
}, |
I'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 thereq
attribute and neitherreq.session
and so on...What I can do is to parse the cookies from
webSocket.upgradeReq.headers.cookie
inonConnect
lifecycle hook, but it seems to me very hacky.The code:
I can't find anything on Apollo Server Docs site (for other topics very well documented!).
Where am I doing wrong?
StackOverflow question: https://stackoverflow.com/questions/52280481/graphql-subscription-websocket-nodejs-express-session-with-apollo-server-2
The text was updated successfully, but these errors were encountered: