Skip to main content

Sessions

A session is server-side state tied to one visitor across multiple requests, the same job express-session does in Express, cookie-signed id on the client, the actual data kept server-side. RapidREST's version works the same way conceptually, with the storage backend chosen for you based on how you've configured your app rather than a store you wire up by hand.

Sessions are opt-in and cost nothing until configured. Reach for one specifically for state that spans more than one request but shouldn't live in a permanent login token, the standard example being a multi-step login flow ("I texted you a code, now tell me what it was") that needs somewhere to hold the pending code between those two requests. Stateless, single-request token auth (a JWT that proves who someone is by itself, every time) doesn't need this at all.

Turning it on

A session is active as soon as a session block exists in your configuration:

conf.defaults({
session: {
secret: 'change-me-in-production',
cookieName: 'rrst.sid', // default
ttl: 1800, // seconds, default: 30 minutes
store: 'memory', // 'memory' | 'redis', default auto-selects
cookieSecure: false, // default
cookieSameSite: 'Lax', // default
cookiePath: '/', // default
},
});

secret is the one required value, it signs the session-id cookie so a visitor can't forge someone else's. Everything else defaults sensibly:

KeyDefaultWhat it means
ttl1800How long, in seconds, a session lasts before expiring on its own
storeautoWhere session data lives, see below
cookieNamerrst.sidThe cookie carrying the session id
cookieSecure / cookieSameSite / cookiePathfalse / Lax / /Standard cookie attributes controlling when the browser sends it back

Where the data lives

The cookie itself only carries a random, signed id, never the session data. That lives server-side, in one of two places:

  • In memory, for local development or a single running instance. Fast, zero setup, but gone on restart and invisible to any other instance of your server.
  • In Redis, a shared external store any instance can read. This is what you need the moment you're running more than one copy of your server. RapidREST switches to it automatically once a cache datastore is configured, no code change required.

Which one is active is a deployment decision, not something your route code needs to know about.

Using it in a route

A session behaves like a plain object on the request, read and written directly:

@Get('/cart')
async getCart(@Request req: HttpRequest) {
req.session ??= {};
req.session.viewCount = (req.session.viewCount ?? 0) + 1;
return { cart: req.session.cart ?? [] };
}

There's no session.save() to remember. Whatever's in req.session once the response finishes is persisted automatically, and a visitor who never triggers one (nothing ever writes to req.session) costs nothing, since no session is created or looked up for them at all.