@fastify/cookie
Fast, secure cookie parsing and signing plugin for Fastify applications
Repository Health
Technical Analysis
@fastify/cookie is the official Fastify plugin for reading, writing, and signing HTTP cookies. It hooks into Fastify’s request lifecycle (onRequest by default, configurable to preParsing, preValidation, or preHandler) to parse incoming Cookie headers into a plain request.cookies object, and decorates the reply with setCookie/cookie and clearCookie helpers that build correct Set-Cookie headers, including support for every modern cookie attribute (SameSite, Partitioned, Priority, HttpOnly, Secure, Domain, Path, Expires, Max-Age).
Beyond basic parsing, the plugin ships a dedicated HMAC-based signer (sha256 by default, any Node crypto algorithm supported) for tamper-proofing cookie values, with built-in support for secret key rotation via an array of secrets so keys can be rotated without invalidating existing sessions. Low-level serialize/parse functions are also exported directly for use outside the request/reply lifecycle. As one of the @fastify/* scoped ecosystem plugins, it is maintained by the core Fastify team and tracks each major Fastify release.
What You Get
- Automatic cookie parsing on request.cookies via a configurable Fastify lifecycle hook (onRequest, preParsing, preValidation, or preHandler)
- reply.setCookie()/reply.cookie() and reply.clearCookie() decorators supporting the full Set-Cookie attribute set (SameSite, Secure, HttpOnly, Domain, Path, Expires, Max-Age, Priority, Partitioned)
- HMAC cookie signing and verification (signCookie/unsignCookie) with configurable algorithm and multi-secret key rotation
- Directly importable serialize/parse functions for manual cookie handling outside the request/reply cycle
- TypeScript typings shipped in the package (types/index.d.ts) with a dedicated tstyche type-test suite
Common Use Cases
- Reading and writing session identifiers or auth tokens as signed, HttpOnly cookies in a Fastify API
- Rotating a cookie-signing secret in production without invalidating currently signed cookies (multi-secret array)
- Setting cross-site cookies correctly with SameSite/Secure/Partitioned for CHIPS-compliant third-party contexts
- Manually serializing or parsing cookie strings outside of an active Fastify request (e.g. in a WebSocket handshake)
Under The Hood
Architecture
The plugin is a single fastify-plugin-wrapped async function (index.js) that decorates the Fastify instance, request, and reply with cookie-related APIs, then registers an onRequest (or configurable alternate) hook to populate request.cookies lazily via a parseCookies helper, plus a single onSend hook (fastifyCookieOnSendHandler) that flushes any queued Set-Cookie values regardless of which parsing hook is active. Pending cookies are tracked per-reply in a Map keyed by name;domain;path (via Symbol-keyed reply properties kReplySetCookies/kReplySetCookiesHookRan) so multiple setCookie calls coalesce correctly, with a fast path that avoids array allocation when only one cookie is set. Signing is fully decoupled into its own module (signer.js) exposing a standalone Signer constructor plus free sign/unsign functions, which the main plugin wires in only when a secret option is supplied.
Tech Stack
A CommonJS Node.js package (Node’s node:crypto and node:test are the only runtime/test primitives used directly) with two runtime dependencies: fastify-plugin for encapsulation-safe registration, and cookie (loaded via a dynamic import() inside an async initializer to bridge the fact that cookie is ESM while this package stays CommonJS, working around Node 20’s lack of require(esm)). Test tooling is node:test with c8 for 100%-enforced coverage and sinon for stubbing, tstyche for a dedicated TypeScript type-test suite, and neostandard/eslint for lint style; CI runs via GitHub Actions.
Code Quality
Tests are extensive: cookie.test.js alone runs to over 1300 lines covering hook variants, attribute combinations, and signing edge cases, backed by a separate signer.test.js for the HMAC signer in isolation, all run under c8 --100, meaning the suite enforces full statement/branch coverage as a hard gate. Error handling is explicit and typed (TypeErrors thrown for invalid hook values, non-string cookie values, and unsupported secrets/algorithms) rather than silently swallowed. Naming is consistent and the module boundary between HTTP-facing decorators and pure signing logic is clean; TypeScript consumers get first-class support via types/index.d.ts plus a tstyche-driven type test file, which is unusually rigorous for a plugin of this size.
API Design
The public surface is intentionally small and mirrors familiar cookie-library idioms (serialize/parse, sign/unsign) so existing knowledge of the underlying cookie and cookie-signature conventions transfers directly. Getting started requires only fastify.register(cookie, { secret }) with no additional boilerplate, and advanced behavior (custom signers, hook placement, key rotation) is opt-in via plain option objects rather than new abstractions, keeping the day-one API and the power-user API the same shape.
Used by 6 apps in this directory
Dittofeed
Marketing · Automation
Open-source omni-channel customer engagement platform for automating transactional and marketing messages via email, SMS, WhatsApp, Slack, and mobile push.
Docmost
Productivity · Note Taking · Collaboration
Self-hosted collaborative wiki and knowledge base with real-time editing, diagrams, AI assistance, and enterprise access controls — a modern alternative to Confluence and Notion.
GraphQL Hive
Developer Tools · Devops · Monitoring
Open-source GraphQL schema registry and observability platform with breaking change detection, federation support, and CI/CD integration for teams of any size.
Infisical
Security · Devops
The open-source platform for secrets, certificates, privileged access, and AI agent security — all in one self-hostable system.
OpenPanel
Analytics
Open-source Mixpanel alternative with session replay, MCP integration, and privacy-first product analytics you fully control.
Palmr.
File Storage · Security
Self-hosted, privacy-focused file sharing without limits