Express res.cookie() Method
What you’ll learn
- How to set cookies with
res.cookie(). - How to use cookie options for security and expiry.
- How to set signed cookies with
cookie-parser. - How to avoid common configuration mistakes.
Syntax
javascript
res.cookie(name, value [, options])1
Set a simple cookie
javascript
app.get('/set-theme', function (req, res) {
res.cookie('theme', 'dark');
res.send('Theme cookie set');
});2
Set secure auth cookie with options
javascript
app.post('/login', function (req, res) {
res.cookie('token', 'abc123', {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 60 * 60 * 1000
});
res.json({ ok: true });
});3
Set a signed cookie
javascript
var cookieParser = require('cookie-parser');
app.use(cookieParser('my-secret'));
app.get('/remember', function (req, res) {
res.cookie('userPref', 'compact', { signed: true, maxAge: 86400000 });
res.send('Signed cookie set');
});⚠️ Common pitfalls
- Use
secure: trueonly with HTTPS or behind a properly configured proxy. - Do not store sensitive raw data in cookie values.
- Set matching options (
path,domain) if you plan to clear cookies later.
❓ FAQ
It sets a cookie by adding a Set-Cookie header to the HTTP response.
Yes, pass options like { httpOnly: true, secure: true } when setting the cookie.
Use maxAge (milliseconds) or expires (Date object) in the options.
Yes, with cookie-parser configured and a secret, use { signed: true }.
sameSite helps protect against CSRF by controlling when cookies are sent on cross-site requests.
Did you know?
res.cookie() sets a Set-Cookie response header and supports security-focused options like httpOnly, secure, and sameSite.
4 people found this page helpful
