Read request cookies
An Express application needs route handlers to read browser cookies as name-value pairs.
Express.js · Module
cookieParser parses the request Cookie header and exposes ordinary values on req.cookies. An optional secret enables validation of signed cookies and exposes valid results on req.signedCookies.
cookie-parser is separate middleware that reads the request Cookie header and exposes name-value pairs through req.cookies. With a secret, it validates signed values, moves valid ones to req.signedCookies, and makes the secret available as req.secret.
cookieParser(secret, options)| Name | Type | Description |
|---|---|---|
secret | string | string[] | A string or array used to sign cookies; optional. An array is tried in order for unsigning. |
options | object | An object passed as the second argument to cookie.parse. |
A middleware function that parses the request Cookie header and populates req.cookies; with a secret, it also populates req.signedCookies.
import express from "express";
import cookieParser from "cookie-parser";
const app = express();
app.use(cookieParser("change-this-secret"));
app.get("/", (req, res) => {
res.json({
cookies: req.cookies,
signedCookies: req.signedCookies
});
});
app.listen(3000);Installs cookie-parser as application middleware, then exposes parsed ordinary and signed cookies on the request.
An Express application needs route handlers to read browser cookies as name-value pairs.
An application uses signed cookies to detect tampering before trusting cookie values.
A handler needs to decode a cookie encoded as JSON.
cookieParser(secret, options) returns middleware that parses the Cookie header. It places ordinary values in req.cookies; with a secret, valid signed values are placed in req.signedCookies.
Follow-up: What happens when the secret is an array? Each secret is tried in order when unsigning the cookie.
The secret is optional. Without one, the middleware still parses ordinary cookies but does not parse signed cookies; with one, it also assigns req.secret and validates signed values.
Follow-up: Where should it be installed? Register it before middleware or route handlers that read req.cookies or req.signedCookies.
JSONCookie(str) converts a JSON cookie value to its parsed value when the value has the JSON-cookie form. Otherwise it returns the original input.
Follow-up: How can a signed value be checked directly? Use signedCookie(str, secret), which returns the unsigned value for a valid signature and false for an invalid one.
cookieParser.JSONCookie(str)cookieParser.signedCookie(str, secret)req.cookiesreq.signedCookiesreq.secretcookie-parser