@fastify/session
Session management plugin for Fastify — server-side sessions with pluggable stores and secure cookie handling.
@fastify/session
FastifySession management plugin for Fastify — server-side sessions with pluggable stores and secure cookie handling.
Fit
Bundle (gzip)
5.5 kB
15.9 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Implementing stateful sessions in Fastify requires secure cookie signing, session ID generation, store adapters, and proper session regeneration to prevent fixation attacks — all with Fastify's async plugin lifecycle.
What It Does
@fastify/session attaches a request.session object to every request. Session data is stored server-side (in-memory, Redis via @fastify/redis, or any connect-compatible store). It handles cookie signing, session regeneration, and destruction for logout flows.
Installation
npm install @fastify/session @fastify/cookieUsage Example
import fastify from 'fastify';
import cookie from '@fastify/cookie';
import session from '@fastify/session';
const app = fastify();
await app.register(cookie);
await app.register(session, {
secret: process.env.SESSION_SECRET!,
cookie: { secure: true, httpOnly: true, maxAge: 86400 },
saveUninitialized: false,
});
app.post('/login', async (request, reply) => {
const user = await authenticate(request.body);
await request.session.regenerate();
request.session.userId = user.id;
return { ok: true };
});Related packages
Auto-load Fastify plugins from a directory — organize routes and plugins as files and let the framework discover them automatically.
@fastify/cookieFastifyPlugin for Fastify that adds support for reading and setting cookies, including signed cookies.
@fastify/corsFastifyCORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
@fastify/helmetFastifySecurity headers plugin for Fastify — sets HTTP headers that protect against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
@fastify/jwtFastifyJWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.