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.