cookie-parser
Cookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
cookie-parser
ExpressCookie parsing middleware for Express — parse Cookie headers into `req.cookies` and support signed cookies for tamper detection.
Fit
Bundle (gzip)
1.8 kB
4.3 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
HTTP cookies arrive as a single Cookie: key=value; key2=value2 header string. Parsing this manually, handling URL encoding, and verifying signed cookies for integrity requires non-trivial boilerplate in every Express app.
What It Does
cookie-parser parses the Cookie header and populates req.cookies with key-value pairs. When configured with a secret, it also populates req.signedCookies — cookies signed with HMAC to detect tampering. Setting cookies uses the standard res.cookie() Express method.
Installation
npm install cookie-parser
npm install -D @types/cookie-parserUsage Example
import cookieParser from 'cookie-parser';
app.use(cookieParser(process.env.COOKIE_SECRET));
app.get('/auth', (req, res) => {
// Set a signed cookie
res.cookie('sessionToken', 'abc123', {
signed: true,
httpOnly: true,
secure: true,
maxAge: 7 * 24 * 60 * 60 * 1000,
});
res.json({ ok: true });
});
app.get('/profile', (req, res) => {
const token = req.signedCookies.sessionToken; // verified or false if tampered
if (!token) return res.status(401).json({ error: 'Unauthorized' });
// ...
});Related packages
Node.js body parsing middleware — populate `req.body` from JSON, urlencoded, text, and raw payloads.
compressionExpressHTTP response compression middleware for Express — gzip/deflate responses to reduce bandwidth and improve load times.
corsExpressCORS middleware for Express — configure cross-origin resource sharing with a single line of code.
express-async-errorsExpressSimplify Express error handling by automatically passing thrown errors to `next()`.
express-fileuploadExpressSimple Express middleware for handling `multipart/form-data` file uploads, built on Busboy.