How to Access Cookie Values in Express Using the Cookie-Parser Middleware
Use the cookie-parser middleware to populate req.cookies for unsigned values and req.signedCookies for signed values, then read them directly in your route handlers.
Express does not parse cookies natively. To access cookie values within your application, you must integrate the community-maintained cookie-parser middleware, which extends the request object with convenient properties for reading both standard and cryptographically signed cookies. This guide demonstrates how to install, configure, and use the middleware based on the official expressjs/express repository implementation.
Understanding the Cookie-Parser Middleware
What Express Doesn’t Do Natively
The core Express framework, as implemented in lib/express.js and lib/application.js, handles routing and middleware composition but deliberately excludes cookie parsing logic. Incoming HTTP requests contain cookies in the raw Cookie header as semicolon-delimited key-value pairs, but without middleware, the req object provides no convenient interface to access these values.
How the Middleware Extends the Request Object
When you register cookie-parser, it attaches a function to the middleware stack that executes on every incoming request. This function:
- Reads the
Cookieheader from the HTTP request. - Parses each
key=valuepair, decodes URL-encoded values, and populatesreq.cookieswith an object map. - If a secret is provided during middleware registration, it verifies signatures on cookies prefixed with
s:and places verified values inreq.signedCookies. - Stores the secret on
req.secretfor use byres.cookiewhen signing outgoing cookies, as implemented inlib/response.js.
Installing and Configuring Cookie-Parser
Install the middleware via npm:
npm install cookie-parser
Register the middleware in your application entry point before your route handlers:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// Register cookie-parser without a secret for unsigned cookies only
app.use(cookieParser());
// Or provide a secret to enable signed cookie verification
app.use(cookieParser('my-secret-key'));
Handling Signed Cookies
When you provide a secret string to cookieParser(), the middleware enables signature verification. Signed cookies contain a cryptographic signature appended to the value, allowing your server to detect tampering. The secret you provide is stored on each request object as req.secret, which res.cookie later uses to sign new cookies, as seen in lib/response.js.
Accessing Cookie Values in Route Handlers
Once the middleware is active, you can access cookie values directly in any route handler.
Reading Unsigned Cookies with req.cookies
The req.cookies object contains key-value pairs for all standard cookies. Access values using standard object notation:
app.get('/greet', (req, res) => {
const username = req.cookies.username || 'guest';
res.send(`Hello, ${username}!`);
});
This reads the username cookie set by the client. If the cookie was URL-encoded, cookie-parser automatically decodes the value before placing it in req.cookies.
Reading Signed Cookies with req.signedCookies
For cookies that were cryptographically signed (typically set with res.cookie using the signed: true option), use req.signedCookies. The middleware verifies the signature against the secret provided during registration. If verification fails (indicating tampering), the cookie is not added to req.signedCookies:
app.get('/dashboard', (req, res) => {
const userId = req.signedCookies.userId;
if (!userId) {
return res.status(401).send('Invalid or missing signed cookie');
}
res.send(`Dashboard for user ${userId}`);
});
According to the test suite in test/req.signedCookies.js, if you attempt to read signed cookies without providing a secret to the middleware, the verification step is skipped and the cookies remain inaccessible through req.signedCookies.
Setting and Clearing Cookies
While cookie-parser handles incoming cookies, Express provides built-in methods for outgoing cookies in lib/response.js. The res.cookie() method serializes values and optionally signs them:
// Set an unsigned cookie
res.cookie('username', 'Alice', { maxAge: 900000, httpOnly: true });
// Set a signed cookie (requires cookie-parser with secret)
res.cookie('userId', '12345', { signed: true, httpOnly: true });
To remove cookies, use res.clearCookie(), which sends a Set-Cookie header with an expiration date in the past:
res.clearCookie('username');
res.clearCookie('userId', { path: '/admin' }); // Must match path used when setting
Summary
- Express does not parse cookies natively; you must install the
cookie-parsermiddleware vianpm install cookie-parser. - Register the middleware with
app.use(cookieParser([secret]))before your routes to populatereq.cookiesand optionallyreq.signedCookies. - Access unsigned cookie values through
req.cookiesand signed values throughreq.signedCookiesin any route handler. - Provide a secret to the middleware to enable signature verification; the secret is stored in
req.secretand used byres.cookie()when setting signed cookies. - Use
res.cookie()andres.clearCookie()(implemented inlib/response.js) to manage outgoing cookies.
Frequently Asked Questions
Do I need cookie-parser to read cookies in Express?
Yes. The core Express framework, as seen in the expressjs/express repository, does not include cookie parsing logic. Without the cookie-parser middleware, the Cookie header remains a raw string and req.cookies is undefined. You must install and register cookie-parser to access parsed cookie values.
What is the difference between req.cookies and req.signedCookies?
req.cookies contains standard key-value pairs for unsigned cookies, while req.signedCookies contains values that have been cryptographically signed to prevent tampering. According to the test file test/req.signedCookies.js, signed cookies are verified against the secret provided to the middleware; if verification fails, the cookie does not appear in req.signedCookies.
How do I set a signed cookie in Express?
Use res.cookie() with the signed: true option, but only after registering cookie-parser with a secret. For example: res.cookie('userId', '12345', { signed: true, httpOnly: true }). The middleware stores the secret in req.secret, which res.cookie (implemented in lib/response.js) uses to generate the signature.
Where is the cookie secret stored in the request object?
The secret provided to cookieParser() is stored in req.secret on every incoming request. This property is used internally by res.cookie() when signing outgoing cookies and by the middleware itself when verifying incoming signed cookies in req.signedCookies.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →