question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Session in webSocket subscriptions

See original GitHub issue

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 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:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:9 (1 by maintainers)

github_iconTop GitHub Comments

5reactions
adaviacommented, Nov 13, 2018

The way i found to deal with this using express session is doing something like this:

subscriptions: {
    onConnect: async (connectionParams, webSocket) => {
      const wsSession = await new Promise(resolve => {
        // use same session parser as normal gql queries
        session(webSocket.upgradeReq, {}, () => {
          if (webSocket.upgradeReq.session) {
            resolve(webSocket.upgradeReq.session);
          }
          return false;
        });
      });
      // We have a good session. attach to context
      if (wsSession.userId) {
        return { session: wsSession };
      }
      // throwing error rejects the connection
      throw new Error('Missing auth token!');
    },
 }
1reaction
adaviacommented, Oct 17, 2018

Any updates on this?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to send websocket message to a specific subscription in ...
I have implemented a WebSocket server using Spring WebSocket and STOMP. There are multiple subscriptions over a single session and I want to ......
Read more >
Building a real-time WebSocket client - AWS AppSync
The following sequence diagram and steps show the real-time subscriptions workflow between the WebSocket client, HTTP client, and AWS AppSync.
Read more >
Spring Session - WebSocket
This guide describes how to use Spring Session to ensure that WebSocket ... Spring Session's WebSocket support works only with Spring's WebSocket support....
Read more >
Maintaining Spring Session with STOMP Websocket - DevGlan
In this post, we will be discussing about how to maintain spring session during websocket connection through HandshakeInterceptor .
Read more >
Handling WebSocket Events | Twitch Developers
If a connection is lost, you must recreate the subscriptions in a new WebSocket session. There is no replay of events that are...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found