We use req.cookies to easily read cookies sent by the browser. The cookie-parser middleware helps Express understand these cookies.
0
0
req.cookies with cookie-parser in Express
Introduction
When you want to remember a user's preferences like theme or language.
When you need to check if a user is logged in by reading a session cookie.
When you want to track user visits or behavior with cookies.
When you want to customize content based on stored cookie data.
When you want to read cookies without manually parsing HTTP headers.
Syntax
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.
Examples
This logs all cookies sent by the browser as an object.
Express
app.use(cookieParser()); app.get('/', (req, res) => { console.log(req.cookies); res.send('Check console for cookies'); });
This reads a cookie named
username and greets the user by name or as 'Guest' if no cookie.Express
app.get('/greet', (req, res) => { const name = req.cookies.username || 'Guest'; res.send(`Hello, ${name}!`); });
This checks a cookie
loggedIn to decide what message to show.Express
app.get('/check', (req, res) => { if (req.cookies.loggedIn === 'true') { res.send('Welcome back!'); } else { res.send('Please log in.'); } });
Sample Program
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.
Express
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'); });
OutputSuccess
Important Notes
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.
Summary
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.