HTTP Session
Introduction
HTTP is stateless, so to remember a user between requests you need a session. @plinthjs/session stores a small bag of data on the server, keyed by a random session id that the browser carries in a cookie. You use it for login state, flash messages after a redirect, remembering form input after a validation failure, and the CSRF token.
pnpm add @plinthjs/sessionThere are three pieces:
- A
SessionStorepersists the data (memory, files, cache, database, optionally encrypted). - A
SessionManagerloads aSessionfrom the store and saves it back. - The
startSession()middleware ties a manager to the request lifecycle.
Configuration
A scaffolded application has src/config/session.ts with these settings, driven by environment variables:
export default {
driver: env('SESSION_DRIVER', 'file'), // 'file' or 'database' are wired by the generated provider
lifetime: env('SESSION_LIFETIME', 120), // minutes
encrypt: env('SESSION_ENCRYPT', false),
files: 'storage/framework/sessions',
table: 'sessions',
cookie: env('SESSION_COOKIE', 'plinth_session'),
path: env('SESSION_PATH', '/'),
domain: env('SESSION_DOMAIN', null),
secure: env('SESSION_SECURE_COOKIE', false),
sameSite: 'lax',
}The generated AuthServiceProvider (src/providers/auth-service-provider.ts) reads this and binds a SessionManager in the container, choosing a FileSessionStore or a DatabaseSessionStore. The cookie, lifetime, secure and domain settings are passed to startSession() in src/server.ts. The other drivers below are available when you build the manager yourself.
INFO
The generated provider reads driver, lifetime, files and table, and src/server.ts reads the cookie options. If you want the cache or encrypted drivers, construct them as shown below and bind that manager in your own provider.
Starting the session
Add startSession() as global middleware. For each request it loads the session named by the cookie (or creates a fresh one), makes it available to your code, then saves it and refreshes the cookie even if a later layer threw.
import { HttpKernel, Router } from '@plinthjs/http'
import { arraySession, startSession } from '@plinthjs/session'
const { manager } = arraySession()
const router = new Router()
const kernel = new HttpKernel(router, {
middleware: [
startSession(manager, {
cookie: 'plinth_session', // default
lifetime: 7200, // cookie Max-Age in seconds, default 2 hours
secure: true, // Secure flag, default false
sameSite: 'Lax', // default 'Lax'
path: '/', // default
// domain: 'example.com', // omitted by default (host-only cookie)
}),
],
})The session cookie is always HttpOnly. Set secure: true in production so it is only sent over HTTPS.
Drivers
Each store implements SessionStore with read, write, destroy and gc. Pick one and give it to a SessionManager.
Array (memory)
Keeps sessions in process memory. Perfect for tests and local experiments, not for production, since sessions vanish on restart and are not shared between processes.
import { arraySession } from '@plinthjs/session'
const { manager, store } = arraySession()File
Stores each session as a JSON file in a directory, creating the directory as needed:
import { FileSessionStore, SessionManager } from '@plinthjs/session'
const manager = new SessionManager(new FileSessionStore('storage/framework/sessions'))Corrupt or partial files are treated as a missing session rather than an error. Session ids are sanitized before being used as file names.
Cache
Stores sessions in any cache with get, put(key, value, seconds) and forget, such as a repository from @plinthjs/cache. Expiry is delegated to the cache's TTL, so this is the right choice for Redis. See Cache and Redis.
import { arrayCache } from '@plinthjs/cache'
import { cacheSession } from '@plinthjs/session'
const { manager } = cacheSession(arrayCache(), {
lifetimeSeconds: 7200, // default
prefix: 'sess:', // key prefix
})Database
Stores sessions in a table, using any connection that has select(sql, bindings) and statement(sql, bindings), such as a Connection from @plinthjs/database. The table needs these columns, which the scaffolded users migration creates as sessions:
await schema.create('sessions', (table) => {
table.string('id').primary()
table.foreignId('user_id').nullable()
table.string('ip_address', 45).nullable()
table.text('user_agent').nullable()
table.text('payload')
table.integer('last_activity')
})import { sqliteConnection } from '@plinthjs/database'
import { databaseSession } from '@plinthjs/session'
const db = sqliteConnection()
const { manager, store } = databaseSession(db, {
table: 'sessions', // default
lifetimeSeconds: 7200, // sessions idle longer than this read as empty
context: () => ({ userId: 1, ipAddress: '10.0.0.1', userAgent: 'curl' }), // optional audit columns
})
await store.gc(7200) // delete rows idle for more than 2 hoursSee Database and Migrations.
Encrypted
Wrap any store to encrypt the whole payload at rest with an object that has encryptString and decryptString, such as the Encrypter from @plinthjs/encryption:
import { Encrypter } from '@plinthjs/encryption'
import { encryptedSession, FileSessionStore } from '@plinthjs/session'
const encrypter = new Encrypter(process.env.APP_KEY!) // a 32 byte key
const { manager } = encryptedSession(new FileSessionStore('storage/framework/sessions'), encrypter)A payload that fails to decrypt (tampered or encrypted with another key) is treated as a missing session, so the user simply starts a new one. See Encryption.
Garbage collection
store.gc(maxLifetimeSeconds) prunes sessions untouched for longer than the lifetime. The array, file and database stores implement it. The cache store does nothing because the cache expires entries itself. Run it from a scheduled task.
Using the session in a request
Inside a handler, session(req) returns the active Session. It throws a 500 with a helpful message if startSession() did not run. Use getSession(req) instead when the session may legitimately be absent, for example in code shared with routes outside the session middleware.
import { getSession, session } from '@plinthjs/session'
router.get('/profile', (req) => {
const s = session(req)
return { name: s.get('name', 'guest') }
})
const maybe = getSession(req) // Session | undefinedReading and writing data
const s = session(req)
s.put('name', 'Ada') // store a value
s.get('name') // => 'Ada'
s.get('missing') // => null
s.get('missing', 'guest') // => 'guest'
s.all() // a copy of everything
s.has('name') // true when present and not null
s.exists('name') // true when the key is present, even if null
s.missing('name') // opposite of has
s.hasAny(['a', 'name']) // any of them present
s.pull('name') // read then delete => 'Ada'
s.forget('name') // delete one key
s.flush() // delete everything
s.only(['a', 'b']) // a subset
s.except(['a']) // everything but
s.replace({ a: 1, b: 2 }) // merge several keys at onceValues must be JSON serializable, since every store persists JSON.
Counters, arrays and caching a value
s.increment('visits') // => 1
s.increment('visits', 5) // => 6
s.decrement('visits') // => 5
s.push('cart', 'sku-1') // append to an array, creating it if needed
s.push('cart', 'sku-2')
s.get('cart') // => ['sku-1', 'sku-2']
s.remember('menu', () => buildMenu()) // compute once, then reuse from the sessionFlash data
Flash data survives for exactly the next request, which is what you want for a "saved" message after a redirect.
router.post('/profile', (req) => {
session(req).flash('status', 'Profile saved') // this request and the next
return Response.redirectTo('/profile')
})
router.get('/profile', (req) => ({ status: session(req).get('status') }))
// first load after the redirect: 'Profile saved'; reload: nullOther flash operations:
s.now('notice', 'Only this request') // available now, gone on the next
s.reflash() // keep everything currently flashed for one more request
s.keep(['status']) // keep only these keys for one more requestYou rarely call flash() by hand. A redirect can queue flash data on the response, and startSession() moves it into the session after your handler returns:
return Response.redirectTo('/profile').with('status', 'Profile saved')See Responses. Under the hood, with('input', ...) goes through flashInput() and every other key through flash().
Old input
When a form fails validation you want to show the previous values again. Response.withInput() flashes the submitted data, and the next request reads it back:
// POST handler
return Response.back(req.header('referer') ?? '/signup')
.withErrors({ email: ['Invalid'] })
.withInput(req.except(['password']))
// the following GET
const s = session(req)
s.old('email') // the previous value, or null
s.old('email', '') // with a fallback
s.old() // the whole bag, {} when none
s.hasOldInput() // any old input?
s.hasOldInput('email')
s.get('errors') // the error bag flashed by withErrors()Never flash secrets. The exception handler's dontFlash list (password, password_confirmation, current_password by default) removes them when it redirects a failed validation for you, see Error handling.
Regenerating and invalidating
Rotate the id whenever privileges change, such as at login, to prevent session fixation:
s.regenerate() // new id and a new CSRF token, data is kept
s.invalidate() // wipe all data and give a new id, used at logoutBoth mint ids through the manager, so they need no arguments. The middleware writes the cookie with the new id on the way out.
SessionManager.start(id) only keeps an id that the store knows. A browser-supplied id the store has never seen is ignored and a fresh id is minted, so an attacker cannot plant a session id of their own choosing. regenerate() and invalidate() also remove the previous id's entry from the store when the manager saves the session, so the old id stops working at once. The SessionGuard from @plinthjs/auth rotates the id on every successful login for you, see Authentication.
The previous URL
The session also has two small helpers for remembering where a user came from:
s.setPreviousUrl('/articles/5')
s.previousUrl() // => '/articles/5', or nullCSRF token
Every session carries a CSRF token, read with s.token() and rotated with s.regenerateToken(). See CSRF protection.
Using the manager directly
The manager is useful outside HTTP, for example in tests and queued jobs:
const { manager } = arraySession()
const s = await manager.start() // a fresh session with a new id
s.put('user_id', 7)
s.flash('status', 'Saved')
await manager.save(s)
const next = await manager.start(s.getId()) // load it again
next.get('user_id') // => 7
next.get('status') // => 'Saved' (flash data is aged once per start)start() ages flash data exactly once per load, so a flash survives one more start() and is then removed.
Testing
Use arraySession() and send requests through a kernel. Carry the cookie between requests yourself:
import { HttpKernel, Request } from '@plinthjs/http'
const kernel = new HttpKernel(router, { middleware: [startSession(manager)] })
const first = await kernel.handle(new Request({ url: '/profile' }))
const cookie = first
.cookies()
.find((c) => c.startsWith('plinth_session='))!
.split(';')[0]
await kernel.handle(new Request({ url: '/profile', headers: { cookie } }))Every collaborator that observes time or randomness accepts an injected clock (now) or id generator (generateId), so expiry and flash lifetimes are deterministic in tests.