`cookie-parser` is an Express.js middleware designed to parse HTTP request cookies, making their values easily accessible through `req.cookies` and `req.signedCookies` properties. The current stable version is 1.4.7, indicating a mature and stable codebase with infrequent but consistent releases primarily focused on dependency updates to ensure compatibility and performance. A key differentiating feature is its robust support for both signed cookies, which helps mitigate tampering, and "JSON cookies," which automatically deserialize JSON-prefixed cookie values. This package provides an essential and convenient layer for web applications built with Express that need to interact with client-side cookies, offering a structured approach to cookie management and enhanced security through optional signing capabilities. It does not handle setting cookies, which is typically done via `res.cookie()` in Express.
npm install cookie-parserVerified import paths — ran on the pinned version, not inferred.
Demonstrates initializing `cookie-parser` with a secret, accessing `req.cookies` and `req.signedCookies`, and setting various types of cookies.
Provide a strong, unique `secret` string (or an array of secrets) when initializing `cookieParser` middleware: `app.use(cookieParser('your-strong-secret-here'))`.Always check for `false` values when accessing cookies from `req.cookies` if signed cookies are expected, or rely solely on `req.signedCookies` for validated values.
Use `res.cookie('name', 'value', { signed: true })` within your Express route handlers to set cookies, leveraging the secret provided to `cookie-parser` for signing.Generate a long, random secret for production environments (e.g., using `crypto.randomBytes(32).toString('hex')`) and manage it securely, preferably via environment variables. For key rotation, ensure the new secret is added to the *beginning* of the secret array.Ensure `app.use(cookieParser(secret))` is called before any routes that depend on `req.cookies` or `req.signedCookies`.
Add `const cookieParser = require('cookie-parser')` at the top of your file.Provide the correct `secret` string (or array of secrets) to `cookieParser` middleware, e.g., `app.use(cookieParser('your-matching-secret'))`.