Skip to main content

Function: createSessionMiddleware()

createSessionMiddleware(mgr): RequestHandler

Defined in: service-core/src/http/session/sessionMiddleware.ts:38

Builds a global, framework-agnostic session middleware backed by the given SessionManager.

req.session is always an object, and req.sessionIsNew tells whether it is backed by a stored session:

  • When the request carries a validly signed session cookie whose session still exists, req.session holds that session's data (req.sessionIsNew === false) and any non-empty data is saved back once the response finishes.
  • Otherwise req.session starts out as an empty, unsaved object (req.sessionIsNew === true). Nothing is stored and no cookie is sent unless a handler explicitly asks for a session by writing to it (setting, defining or deleting a property, or assigning a new object to req.session). The first such write issues a fresh session ID via Set-Cookie, and the data is saved once the response finishes. A write after the response headers were sent can no longer deliver the cookie, so it isn't saved.

This keeps clients that never send cookies (e.g. API clients authenticating with a bearer token) from creating a new stored session on every request. Middleware that only records bookkeeping about the caller (last access time, IP address, ...) should skip req.session when req.sessionIsNew is true.

Parameters​

mgr​

SessionManager

Returns​

RequestHandler