We use req.cookies to easily read cookies sent by the browser. The cookie-parser middleware helps Express understand these cookies.
req.cookies with cookie-parser in Express
const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.get('/', (req, res) => { const cookies = req.cookies; // use cookies object });
Call app.use(cookieParser()) before your routes to enable cookie parsing.
req.cookies is an object where each cookie name is a key and its value is the cookie value.
app.use(cookieParser()); app.get('/', (req, res) => { console.log(req.cookies); res.send('Check console for cookies'); });
username and greets the user by name or as 'Guest' if no cookie.app.get('/greet', (req, res) => { const name = req.cookies.username || 'Guest'; res.send(`Hello, ${name}!`); });
loggedIn to decide what message to show.app.get('/check', (req, res) => { if (req.cookies.loggedIn === 'true') { res.send('Welcome back!'); } else { res.send('Please log in.'); } });
This Express app sets a cookie named username with value 'Alice' at /setcookie. Then at /showcookie, it reads and shows the cookie value using req.cookies.
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser()); app.get('/setcookie', (req, res) => { res.cookie('username', 'Alice'); res.send('Cookie has been set'); }); app.get('/showcookie', (req, res) => { const user = req.cookies.username || 'No cookie found'; res.send(`Username cookie value: ${user}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Cookies are sent by the browser with each request, so req.cookies is available only after cookie-parser middleware runs.
Cookies are strings. If you store JSON, you need to parse it yourself.
For security, avoid storing sensitive info directly in cookies.
req.cookies holds cookies sent by the browser as an object.
cookie-parser middleware must be used to fill req.cookies.
Use cookies to remember user info or preferences easily.
Practice
req.cookies represent in an Express app when using cookie-parser middleware?Solution
Step 1: Understand the role of
Thecookie-parsercookie-parsermiddleware parses cookies from the HTTP request headers.Step 2: Identify what
After parsing,req.cookiesholdsreq.cookiesis an object where each cookie name is a key and its value is the cookie's value.Final Answer:
An object containing cookies sent by the browser -> Option BQuick Check:
req.cookies= object of cookies [OK]
req.cookies is an object, not a string or function [OK]- Thinking
req.cookiesis a function - Expecting
req.cookiesto be a string - Confusing
req.cookieswith response cookies
cookie-parser middleware in an Express app?Solution
Step 1: Recall middleware usage in Express
Middleware functions are added usingapp.use()and must be called as functions if they return middleware.Step 2: Apply this to
The correct syntax iscookie-parserapp.use(cookieParser());to invoke the function and add the middleware.Final Answer:
app.use(cookieParser()); -> Option CQuick Check:
Middleware added withapp.use(cookieParser())[OK]
- Forgetting parentheses after cookieParser
- Calling cookieParser as a method on app
- Passing cookieParser without calling it
cookie-parser middleware, what will be the output if the browser sends a cookie named user with value alice?
app.get('/profile', (req, res) => {
res.send(`User: ${req.cookies.user}`);
});Solution
Step 1: Check if
Assumingcookie-parseris usedcookie-parsermiddleware is active,req.cookiescontains parsed cookies.Step 2: Access the
The code accessesusercookie valuereq.cookies.user, which equals 'alice' from the browser cookie.Final Answer:
User: alice -> Option DQuick Check:
Cookie value accessed correctly = User: alice [OK]
- Not using cookie-parser so req.cookies is undefined
- Trying to access cookies as a string
- Assuming cookie names are case-insensitive
req.cookies is always undefined?
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.get('/', (req, res) => {
res.send(req.cookies);
});
app.use(cookieParser());
Solution
Step 1: Check middleware order
Middleware must be added before routes to affectreqobjects in those routes.Step 2: Identify the problem in code
Here,app.use(cookieParser())is after the route, soreq.cookiesis not set when the route runs.Final Answer:
cookie-parsermiddleware is added after the route, soreq.cookiesis undefined -> Option AQuick Check:
Middleware order matters =cookie-parsermiddleware is added after the route, soreq.cookiesis undefined [OK]
req.cookies [OK]- Placing middleware after routes
- Confusing
req.cookieswithres.cookies - Not calling cookieParser as a function
theme and sends back 'Dark mode' if its value is 'dark', otherwise 'Light mode'. Which code correctly implements this using req.cookies with cookie-parser?Solution
Step 1: Check cookie access and comparison
Use strict equality===to comparereq.cookies.themeto the string 'dark'.Step 2: Identify correct syntax
app.get('/mode', (req, res) => { if (req.cookies.theme === 'dark') res.send('Dark mode'); else res.send('Light mode'); }); uses===and string 'dark' correctly. app.get('/mode', (req, res) => { if (req.cookies['theme'] = 'dark') res.send('Dark mode'); else res.send('Light mode'); }); uses assignment=instead of comparison. app.get('/mode', (req, res) => { if (req.cookies.theme == dark) res.send('Dark mode'); else res.send('Light mode'); }); uses loose equality==with unquoteddark. app.get('/mode', (req, res) => { if (req.cookies.theme === dark) res.send('Dark mode'); else res.send('Light mode'); }); uses undefined variabledarkwithout quotes.Final Answer:
The code using strict equalityreq.cookies.theme === 'dark'-> Option AQuick Check:
Use=== 'dark'to compare cookie value [OK]
- Using = instead of === for comparison
- Not quoting string literals
- Using loose equality == instead of ===
Ready to prove it?
Pass the test and this pattern moves unknown
