{"id":15991,"library":"cookie-parser","title":"HTTP Cookie Parsing Middleware","description":"`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.","status":"active","version":"1.4.7","language":"javascript","source_language":"en","source_url":"https://github.com/expressjs/cookie-parser","tags":["javascript","cookie","middleware"],"install":[{"cmd":"npm install cookie-parser","lang":"bash","label":"npm"},{"cmd":"yarn add cookie-parser","lang":"bash","label":"yarn"},{"cmd":"pnpm add cookie-parser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for parsing cookie strings and handling options.","package":"cookie","optional":false},{"reason":"Used internally for signing and unsigning cookie values to prevent tampering.","package":"cookie-signature","optional":false}],"imports":[{"note":"This package is a CommonJS module. Use `require` for Node.js applications.","wrong":"import cookieParser from 'cookie-parser'","symbol":"cookieParser","correct":"const cookieParser = require('cookie-parser')"},{"note":"Static methods are accessed via the main `cookieParser` export in CommonJS.","wrong":"import { signedCookie } from 'cookie-parser'","symbol":"cookieParser.signedCookie","correct":"const { signedCookie } = require('cookie-parser'); // or cookieParser.signedCookie"},{"note":"Static methods are available on the `cookieParser` function itself; destructuring `require` is also possible.","wrong":"import { JSONCookie } from 'cookie-parser'","symbol":"cookieParser.JSONCookie","correct":"const { JSONCookie } = require('cookie-parser'); // or cookieParser.JSONCookie"}],"quickstart":{"code":"const express = require('express');\nconst cookieParser = require('cookie-parser');\n\nconst app = express();\nconst PORT = 3000;\nconst SECRET_KEY = process.env.COOKIE_SECRET || 'my-secret-key-for-signing';\n\napp.use(cookieParser(SECRET_KEY));\n\napp.get('/', (req, res) => {\n  // Access raw and signed cookies from the request\n  console.log('Raw Cookies:', req.cookies);\n  console.log('Signed Cookies:', req.signedCookies);\n\n  // Example of setting a regular and a signed cookie\n  res.cookie('regular', 'hello world', { maxAge: 900000, httpOnly: true });\n  res.cookie('signed', 'secret message', { maxAge: 900000, httpOnly: true, signed: true });\n  res.cookie('json_data', 'j:{\"user\":\"test\"}', { maxAge: 900000, httpOnly: true });\n\n  res.send('Check your console for cookie logs and browser for new cookies!\\n' +\n           'Send a request with cookies like: curl http://localhost:3000 --cookie \"Cho=Kim;Greet=Hello;signed=s%3Asecret%20message.hS7...;json_data=j%3A%7B%22user%22%3A%22test%22%7D\"');\n});\n\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log('Remember to restart the server if you change COOKIE_SECRET environment variable.');\n});","lang":"javascript","description":"Demonstrates initializing `cookie-parser` with a secret, accessing `req.cookies` and `req.signedCookies`, and setting various types of cookies."},"warnings":[{"fix":"Provide a strong, unique `secret` string (or an array of secrets) when initializing `cookieParser` middleware: `app.use(cookieParser('your-strong-secret-here'))`.","message":"If `cookie-parser` is initialized without a `secret` string or array, it will not parse or expose signed cookies. `req.signedCookies` will remain an empty object, even if signed cookies are present in the request.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"Cookies that are signed but fail signature validation will appear as `false` in `req.cookies` instead of being moved to `req.signedCookies`. This can lead to unexpected `false` values if not explicitly checked.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Use `res.cookie('name', 'value', { signed: true })` within your Express route handlers to set cookies, leveraging the secret provided to `cookie-parser` for signing.","message":"This middleware only *parses* cookies from the incoming request. It does not provide functionality for *setting* cookies in the response. For setting cookies, use Express's `res.cookie()` or a similar method from your web framework.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"The `secret` used for `cookieParser` should be a strong, randomly generated string and kept confidential. If an array of secrets is provided, they are tried in order for unsigning, which can be useful for key rotation. However, exposing or reusing secrets compromises cookie security.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `app.use(cookieParser(secret))` is called before any routes that depend on `req.cookies` or `req.signedCookies`.","cause":"The `cookie-parser` middleware has not been applied to the Express application, or it's applied after the route that attempts to access `req.cookies`.","error":"TypeError: Cannot read properties of undefined (reading 'cookies')"},{"fix":"Add `const cookieParser = require('cookie-parser')` at the top of your file.","cause":"The `cookie-parser` module was not correctly imported using CommonJS `require`.","error":"ReferenceError: cookieParser is not defined"},{"fix":"Provide the correct `secret` string (or array of secrets) to `cookieParser` middleware, e.g., `app.use(cookieParser('your-matching-secret'))`.","cause":"The `cookieParser` middleware was initialized without a `secret`, or the `secret` provided does not match the one used to sign the cookies.","error":"Signed cookies are not being parsed or showing up in `req.signedCookies`."}],"ecosystem":"npm"}