When using fastify-session and fastify-webockets, how do I get access to the session?

1.7k views Asked by At

When I use both fastify-websocket and fastify-session in my Fastify app, I run into an issue.

  fastify.get( myWebsocketPath, websocket: true },
               async (connection, rawRequest) => {

    console.log(`request for websocket connection`)
    if( request.session.authenticated ) {
      myApi( connection.socket )
    }
  })

Except this fails because I only have the rawRequest, not the regular request decorated with the session.

1

There are 1 answers

0
eadsjr On

It seems that to get an external handle for it you need to set the session store yourself. It's better to use a custom store, but for simplicity in this example I will use the built-in one provided by fastify-session.

let fastifySession = require(`fastify-session`)
let mySessionStore = new fastifySession.MemoryStore /// TODO: customize
let options = { store: mySessionStore, secret: `itsasecrettoeverybody`,  cookieName: `sessionId`, expires: 3600000, cookie:  { secure: false } }
fastify.register(fastifySession, options)

// ...

const routes = async (fastify, options) => {
  fastify.get( myWebsocketPath, websocket: true },
               async (connection, rawRequest) => {

    /// Retrieve the session
    let cookies = rawRequest.headers.cookie.split(`;`)
    for( c of cookies ) {
      if( c.startsWith(`sessionId=`) ) {

        /// Get SessionID from the cookie
        let sessionID = c.substring(10).trim()
        sessionID = sessionID.substring( 0, sessionID.indexOf(`.`) )

        /// Collect session and check the authentication state.
        mySessionStore.get( sessionID, ( o, session ) => {
          if( session != null && session.authenticated == true ) {
            myApi( connection.socket )
          }
        })
        break
      }
    }
  })
}

Credit to Zekth for pointing me in the right direction.