Full answer
HTTP is stateless, so cookies carry state between requests, most often a session identifier. The server sends Set-Cookie: sid=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600. The browser stores it and adds Cookie: sid=abc123 to later requests that match the cookie's rules. Each cookie is limited to roughly 4 KB.
The attributes control behavior:
Max-Age(seconds) orExpires(a date) sets the lifetime. Without both, it is a session cookie that ends when the browser session ends. SettingMax-Age=0deletes it.DomainandPathdefine scope. WithoutDomain, the cookie goes only to the exact host that set it. Setting a parent domain shares it with subdomains.Securesends the cookie only over HTTPS.HttpOnlymakes it invisible todocument.cookie, which limits what an injected script can steal.SameSite=Strictsends the cookie only for same-site requests,Laxalso sends it for top-level navigations such as clicking a link, andNone(which requiresSecure) sends it in all contexts. Browsers treat a missing value asLax. This reduces cross-site request forgery.- The
__Host-name prefix forcesSecure,Path=/, and noDomain, which is the strictest scope.
document.cookie reads all non-HttpOnly cookies as one string, and assigning to it sets or updates one cookie at a time, which is awkward. The newer Cookie Store API is a cleaner interface in supporting browsers.
Cookies are sent on every matching request, including images, so large cookies slow pages down. For data that the server does not need, localStorage avoids that cost. Authentication tokens in cookies should use HttpOnly and Secure, and state-changing endpoints still need CSRF protection.
const http = require('node:http');
const server = http.createServer((req, res) => {
res.setHeader('Set-Cookie', [
'sid=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=3600',
'theme=dark; Path=/; Max-Age=31536000',
'__Host-token=t1; Secure; Path=/; SameSite=Strict',
]);
res.end(`you sent: ${req.headers.cookie ?? 'no cookie'}`);
});
function parseSetCookie(header) {
const [pair, ...attributes] = header.split(';').map((part) => part.trim());
const [name, ...rest] = pair.split('=');
const result = { name, value: rest.join('='), httpOnly: false, secure: false };
for (const attribute of attributes) {
const [key, value = ''] = attribute.split('=');
const lower = key.toLowerCase();
if (lower === 'httponly') result.httpOnly = true;
else if (lower === 'secure') result.secure = true;
else if (lower === 'samesite') result.sameSite = value;
else if (lower === 'max-age') result.maxAgeSeconds = Number(value);
else if (lower === 'path') result.path = value;
}
return result;
}
function visibleToScript(cookies) {
return cookies.filter((cookie) => !cookie.httpOnly).map((cookie) => `${cookie.name}=${cookie.value}`).join('; ');
}
server.listen(0, '127.0.0.1', async () => {
const response = await fetch(`http://127.0.0.1:${server.address().port}/`);
const cookies = response.headers.getSetCookie().map(parseSetCookie);
console.table(cookies.map(({ name, httpOnly, secure, sameSite, maxAgeSeconds }) => ({ name, httpOnly, secure, sameSite, maxAgeSeconds })));
console.log('readable by document.cookie:', visibleToScript(cookies));
const withCookie = await fetch(`http://127.0.0.1:${server.address().port}/`, {
headers: { Cookie: 'sid=abc123; theme=dark' },
});
console.log(await withCookie.text());
const deleteHeader = 'sid=; Path=/; Max-Age=0';
console.log(parseSetCookie(deleteHeader));
server.close();
server.closeAllConnections();
});Run with Node.js v24.22.1 as js-79.js; two runs gave identical output. Output: ┌─────────┬────────────────┬──────────┬────────┬───────────┬───────────────┐ │ (index) │ name │ httpOnly │ secure │ sameSite │ maxAgeSeconds │ ├─────────┼────────────────┼──────────┼────────┼───────────┼───────────────┤ │ 0 │ 'sid' │ true │ true │ 'Lax' │ 3600 │ │ 1 │ 'theme' │ false │ false │ undefined │ 31536000 │ │ 2 │ '__Host-token' │ false │ true │ 'Strict' │ undefined │ └─────────┴────────────────┴──────────┴────────┴───────────┴───────────────┘ readable by document.cookie: theme=dark; __Host-token=t1 you sent: sid=abc123; theme=dark { name: 'sid', value: '', httpOnly: false, secure: false, path: '/', maxAgeSeconds: 0 }
Key points
- The server sets a cookie with Set-Cookie; the browser returns it in a Cookie header.
- HttpOnly hides it from scripts; Secure limits it to HTTPS.
- SameSite (Strict, Lax, None) controls cross-site sending; missing means Lax in browsers.
- Domain and Path set scope; Max-Age or Expires sets lifetime; Max-Age=0 deletes.
- Cookies are sent on every matching request, so keep them small.
Common mistakes
- Storing session tokens in cookies without HttpOnly and Secure.
- Setting SameSite=None without Secure; browsers reject it.
- Assuming Domain is optional for sharing with subdomains; leaving it out keeps the cookie host-only.
- Putting large data in cookies, which is then sent on every request.
Follow-ups
- How do SameSite=Lax and Strict differ for a link clicked on another site?
- Why does SameSite not remove the need for CSRF tokens in every case?
- What is the difference between a session cookie and a persistent cookie?
Tips
- Name the three security attributes in one breath: HttpOnly, Secure, SameSite.
- Explain what each protects against: script theft, network sniffing, and cross-site requests.
- Mention that cookies travel with every request, so size matters.