Preference cookies
Persist a short-lived browser preference such as a theme selection.
Express.js · Function
res.cookie() adds a named cookie to an Express response by setting the HTTP Set-Cookie header. It accepts string or JSON-serialized object values and optional attributes for lifetime, scope, encoding, and security.
Call res.cookie() on a response to add a Set-Cookie header. The value can be text or an object that Express serializes as JSON, while the options object controls attributes such as lifetime, scope, encoding, security, and signing; the method returns the response so calls can be chained.
res.cookie(name, value [, options])| Name | Type | Description |
|---|---|---|
name | String | Cookie name. |
value | String | Object | Cookie value; objects are serialized as JSON. |
options | Object | undefined | Attributes for the Set-Cookie header, including domain, encode, expires, httpOnly, maxAge, path, partitioned, priority, secure, signed, and sameSite. |
Response; sets cookie name to value.
const express = require('express');
const app = express();
app.get('/preferences', (req, res) => {
res.cookie('theme', 'dark', {
httpOnly: true,
maxAge: 900000,
sameSite: 'lax'
});
res.json({ok: true});
});
app.listen(3000);This route sets a cookie with server-only access, a 15-minute lifetime, and a SameSite policy before returning JSON.
Persist a short-lived browser preference such as a theme selection.
Issue an HTTP-only cookie for a server-managed login or session identifier.
Apply domain, path, expiry, SameSite, or HTTPS constraints to a cookie.
res.cookie() sets the response's HTTP Set-Cookie header and returns the Response object. Its value may be a string or an object, with objects serialized as JSON.
Follow-up: How would you set several cookies? Call res.cookie() multiple times on the same response; the documentation explicitly supports that pattern.
The options object configures cookie attributes, including domain, path, expiry, maxAge, httpOnly, secure, sameSite, partitioned, priority, signed, and encode. The path defaults to /.
Follow-up: What is the difference between expires and maxAge? expires is an absolute GMT Date, while maxAge expresses expiry relative to now in milliseconds.
A string is used as the cookie value directly, while an object is serialized as JSON. The encode option selects a synchronous value-encoding function and defaults to encodeURIComponent.
Follow-up: Can encode perform asynchronous work? No; the documentation says asynchronous encoding functions are unsupported.
res.clearCookie()res.set()res.get()cookie-parser