Working with Cookies
1. Installing cookie-parser
| Command | Purpose |
npm i cookie-parser | Reads cookies into req.cookies |
npm i cookie | Lower-level serialize/parse only |
2. Using cookie-parser Middleware
Example: With secret for signing
import cookieParser from "cookie-parser";
app.use(cookieParser(env.COOKIE_SECRET)); // string or array of strings (rotation)
3. Reading Cookies
| Property | Detail |
req.cookies | Plain unsigned cookies |
req.signedCookies | Signed cookies (verified) |
Example: Read both
const lang = req.cookies.lang || "en";
const userId = req.signedCookies.userId; // false if signature invalid
4. Setting Cookies
Example: Secure session cookie
res.cookie("session", token, {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
path: "/",
domain: ".example.com"
});
5. Deleting Cookies
| Method | Notes |
res.clearCookie(name, opts) | Sends Set-Cookie with past expiry |
| Same opts required | path and domain MUST match the original |
Example: Logout
res.clearCookie("session", { path: "/", domain: ".example.com" });
6. Setting Cookie Options
| Option | Purpose |
maxAge | Lifetime in ms (preferred) |
expires | Date object |
httpOnly | Not accessible via JS (XSS protection) |
secure | HTTPS only |
sameSite | "strict", "lax", "none" |
signed | Sign with cookieParser secret |
path | URL prefix where sent (default /) |
domain | Send to subdomains |
priority | "low", "medium", "high" |
partitioned | CHIPS — third-party cookie isolation NEW |
7. Using Signed Cookies
Example: Signed user cookie
res.cookie("userId", String(user.id), {
signed: true,
httpOnly: true,
sameSite: "lax",
secure: true
});
Note: Signing prevents tampering, NOT eavesdropping. Always pair with httpOnly + secure for sensitive cookies.
8. Reading Signed Cookies
| Result | Meaning |
| String value | Signature valid |
false | Signature invalid (tampered) |
undefined | Cookie not set |
Example: Verify signed cookie
const userId = req.signedCookies.userId;
if (userId === false) return res.status(401).json({ error: "Tampered cookie" });
9. Setting Cookie Path and Domain
| Scenario | Setting |
| Subdomain sharing | domain: ".example.com" |
| Single domain | Omit domain |
| Admin section only | path: "/admin" |
10. Using SameSite Attribute
| Value | Sent on cross-site | CSRF protection |
strict | Never | Strongest |
lax (browser default) | Top-level GET nav only | Strong |
none | Always (requires secure) | None — needs CSRF tokens |
Warning: SameSite=None requires Secure. Most browsers default to Lax when unspecified.