MatthewWid / better-sse

⬆ Dead simple, dependency-less, spec-compliant server-sent events implementation for Node, written in TypeScript.
MIT License
485 stars 14 forks source link

Storing sessions? Detecting closed session? #46

Closed qpwo closed 2 years ago

qpwo commented 2 years ago

I want to keep track of which user is on which session, and persist that across browser refresh. How would you recommend I go about this? I could store it in an object. Should I use something like express-session?

Example:

import express from 'express'
import { createSession } from 'better-sse'

const app = express()

app.use(express.static('./public'))

app.get('/sse', async (req, res) => {
    const session = await createSession(req, res)
    session.state.id = Math.random().toString().slice(5)
    res.sse = session
})

app.get('/send-me-my-id', async (req, res) => {
    console.log({ 'res-sse': res.sse }) // undefined!!
    res?.sse?.push(res.sse?.state?.id, 'id')
})

app.listen(8080)

Can the server be notified when the client has stopped listening? I could poll isConnected, but something like .onDisconnect(...) would be nice.

Great library btw!!

MatthewWid commented 2 years ago

Can the server be notified when the client has stopped listening? I could poll isConnected, but something like .onDisconnect(...) would be nice.

Session extends from EventEmitter and emits the disconnected event when the connection is closed.

I want to keep track of which user is on which session, and persist that across browser refresh. How would you recommend I go about this? I could store it in an object. Should I use something like express-session?

There's a bit of overlapping terminology here which may be a bit confusing. From the getting started guide in the context of Better SSE, a session is simply a single open connection between a client and server, it does not persist between browser refreshes or different pages so you'll need to use your own mechanism for that.

In some libraries that use Better SSE, for example, I have seen a pattern of creating a map (just a simple object or Set) with the user ID for the key and a dedicated Channel as the value. Then whenever a user connects you lookup if there is a channel for their ID and then simply register the session with that channel.

This allows you to track whether the user is currently connected at all (simply check that Channel#activeSessions is more than one (1)) and also works if the user opens multiple tabs at once as they can have multiple sessions for themselves in that one channel.

This is probably the way I'd go about it too, and yes, you'd need some way to track the session with a cookie or some other method which express-session seems to be designed for.

qpwo commented 2 years ago

Thank you I'll try this