Cookies
Set cookies with res.cookie and read them with cookie-parser.
Syntax
res.cookie(name, value, options)Cookies store small pieces of data in the browser and are sent back on every request. Express can set cookies with res.cookie() out of the box. To read them, add the cookie-parser middleware (npm install cookie-parser), which fills req.cookies.
Example
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/set', (req, res) => {
res.cookie('theme', 'dark', { httpOnly: true });
res.send('Cookie set');
});
app.get('/read', (req, res) => {
res.send('Theme is ' + req.cookies.theme);
});When to use it
- A session-based auth system sets a signed session cookie on login and reads it back on subsequent requests to identify the user.
- An analytics service stores a visitor's preference in a cookie with a 30-day expiry so returning users see the same settings.
- A developer uses cookie-parser middleware to read a theme preference cookie and serve the matching CSS file.
More examples
Setting a cookie on login
Sets an httpOnly cookie named 'token' with a 1-day expiry, preventing JavaScript from reading it.
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.post('/login', (req, res) => {
res.cookie('token', 'abc123', {
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000, // 1 day
});
res.json({ loggedIn: true });
});Reading a cookie
Reads the 'token' cookie from req.cookies (populated by cookie-parser) and returns a 401 if it is missing.
const cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/me', (req, res) => {
const token = req.cookies.token;
if (!token) return res.status(401).json({ error: 'Not logged in' });
res.json({ token });
});Clearing a cookie on logout
Calls res.clearCookie() with the same options as the original cookie to ensure the browser removes it.
app.post('/logout', (req, res) => {
res.clearCookie('token', { httpOnly: true });
res.json({ loggedOut: true });
});
Discussion