req.cookies contain after using cookie-parser?Consider an Express app using cookie-parser middleware. A client sends a request with the header Cookie: user=alice; theme=dark. What will req.cookies contain inside a route handler?
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser()); app.get('/', (req, res) => { res.json(req.cookies); });
Think about how cookie-parser parses the cookie header into an object.
The cookie-parser middleware parses the cookie header string into an object where each cookie name is a key and its value is the value. So req.cookies is an object like { user: 'alice', theme: 'dark' }.
cookie-parser to access cookies?Which of the following Express app snippets correctly sets up cookie-parser and accesses a cookie named sessionId?
Remember to call cookieParser() as a function and use req.cookies (plural).
Option C correctly calls cookieParser() middleware before routes and accesses req.cookies.sessionId. Option C applies middleware after routes, so cookies won't be parsed. Option C passes the middleware function without calling it. Option C uses req.cookie instead of req.cookies.
req.cookies remain empty despite sending cookies?An Express app uses cookie-parser middleware. The client sends cookies, but req.cookies is always empty. What is the most likely cause?
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.get('/', (req, res) => { res.json(req.cookies); }); app.use(cookieParser());
Middleware order matters in Express.
Middleware must be registered before routes to affect them. Here, cookie-parser is registered after the route, so req.cookies is empty inside the route handler.
req.signedCookies after using cookie-parser('secret')?Given the Express app below, what will req.signedCookies contain if the client sends a cookie token=abc123 signed with the secret secret?
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser('secret')); app.get('/', (req, res) => { res.json({ cookies: req.cookies, signedCookies: req.signedCookies }); });
Signed cookies are verified and available in req.signedCookies.
When cookie-parser is initialized with a secret, it verifies signed cookies. If the signature matches, the cookie appears in req.signedCookies. So req.signedCookies contains the verified cookie { token: 'abc123' }.
cookie-parser and req.cookies is TRUE?Choose the correct statement about how cookie-parser works with req.cookies in Express.
Think about what cookie-parser does and what req.cookies holds.
cookie-parser reads the Cookie header and creates an object req.cookies with cookie names and values. It does not encrypt cookies; encryption is done elsewhere. req.cookies is not available without middleware. Signed cookies appear in req.signedCookies, not req.cookies.