@fastify/session

A server-side session plugin for Fastify with signed cookies, pluggable stores, and first-class TypeScript support.

Library
npm
v11.1.2
129stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
78/100Good
Development Activity68
Maintenance84
Community84
Maturity56
Momentum20

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
76/100Good
Architecture85
Code Quality90
Innovation85
Learning Curve45

@fastify/session decorates the Fastify request with a session object backed by a server-side store, giving applications stateful sessions without hand-rolling cookie signing or storage logic. It requires the companion @fastify/cookie plugin to sign and parse the session cookie, and ships with a simple in-memory store for development while supporting any store compatible with the express-session store interface (Redis, Mongo, file-based, and more) for production use.

The plugin is the continuation of the now-unmaintained fastify-session package, carried forward and maintained by the Fastify core team. It exposes a small, well-documented API — get, set, destroy, reload, save, touch, regenerate, isModified, isSaved — each supporting both callback and Promise styles, plus a decryptSession decorator for manually decrypting a session outside the normal request lifecycle. TypeScript users can extend the Session interface via declaration merging to get fully typed session data.

What You Get

  • A request.session decorator with get/set/destroy/reload/save/touch/regenerate methods, each usable with callbacks or Promises
  • Signed, tamper-evident session cookies via @fastify/cookie, with support for secret rotation using an array of secrets
  • A pluggable store interface compatible with the existing express-session store ecosystem (Redis, Mongo, file-based stores, etc.), plus a built-in in-memory MemoryStore for development
  • Full TypeScript declarations with a documented pattern for augmenting the Session interface with application-specific fields
  • Fine-grained cookie controls — custom cookie name/prefix, path scoping, secure/sameSite/partitioned attributes, and rolling expiration
  • A fastify.decryptSession decorator for verifying and decrypting a session cookie outside the normal request/response cycle

Common Use Cases

  • Server-rendered Fastify applications that need logged-in user state without a full auth framework
  • APIs that need short-lived, revocable session identifiers instead of long-lived JWTs
  • Migrating an Express app using express-session to Fastify while reusing the same session store
  • Multi-instance deployments that externalize session state to Redis or Mongo via a shared store
  • Applications rotating signing secrets on a schedule while keeping existing sessions valid

Under The Hood

Architecture The plugin entry point (index.js) is wrapped with fastify-plugin and declares a hard dependency on @fastify/cookie, registering an onRequest hook that reads the session cookie and instantiates a Session (lib/session.js), and an onSend hook that persists the session back to the store and writes the Set-Cookie header only when the session was modified or created. Session itself keeps its internal state (store reference, id generator, cookie signer, request) behind Symbol keys to avoid leaking implementation details onto the object shape serialized to the store, and computes a SHA-256 hash of its own serialized state (via safe-stable-stringify) to cheaply detect whether a session has been modified since it was loaded. The default Store (lib/store.js) is a thin EventEmitter-based Map wrapper matching the set/get/destroy callback interface used throughout the express-session store ecosystem, so third-party stores are drop-in compatible. lib/idGenerator.js generates session ids from a pooled buffer of crypto.randomBytes, refilling the pool once exhausted, which avoids a syscall on every request.

Tech Stack Plain CommonJS JavaScript with hand-written TypeScript declarations (types/index.d.ts) validated separately via tstyche type tests. Runtime dependencies are minimal and deliberate: fastify-plugin for correct plugin encapsulation and safe-stable-stringify for deterministic, circular-reference-safe session hashing. The project targets Fastify 5.x and Node’s built-in node:test runner rather than a third-party test framework, with c8 enforcing coverage and eslint (via the neostandard shared config) enforcing style. A benchmark/ directory using cronometro supports performance regression checks, and examples/ demonstrates wiring up in-memory and Redis-backed stores.

Code Quality The test suite spans nine files and roughly 3,500 lines covering cookie parsing, path-scoping (verifyPath), id generation, option validation, expiration handling, and store behavior, run via node:test with c8 --100 enforcing full statement coverage — there is no tolerance for untested branches in CI. Errors are handled explicitly: checkOptions validates the secret option up front and returns a descriptive Error rather than throwing deep in the request cycle, and store callbacks propagate errors through both the callback and Promise-returning code paths. Naming is consistent camelCase throughout, private state is enforced via Symbol keys rather than underscore-prefixed conventions, and the .d.ts file is exercised by its own tstyche type-test file rather than left unverified.

What Makes It Unique Rather than introducing a bespoke session abstraction, the plugin deliberately mirrors the express-session store contract (set/get/destroy callbacks), which means the large existing ecosystem of Express session stores works with a Fastify app with no adapter layer. Session mutation detection is done by hashing the session’s own serialized state rather than tracking a dirty flag on every mutator, which keeps the public get/set API surface trivially simple while still letting onSend skip unnecessary store writes and cookie rewrites for untouched sessions.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search