← Back to JavaScript, page 4

javascript-0079 · Medium mid

How do cookies work, and what do the HttpOnly, Secure, SameSite, Domain, Path, and expiry attributes do?

A cookie is a small name-value pair the server sets with a Set-Cookie header and the browser sends back with matching requests. HttpOnly hides it from JavaScript, Secure limits it to HTTPS, SameSite controls cross-site sending, Domain and Path decide which requests include it, and Max-Age or Expires set its lifetime. Session cookies for logins should use HttpOnly, Secure, and SameSite.

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) or Expires (a date) sets the lifetime. Without both, it is a session cookie that ends when the browser session ends. Setting Max-Age=0 deletes it.
  • Domain and Path define scope. Without Domain, the cookie goes only to the exact host that set it. Setting a parent domain shares it with subdomains.
  • Secure sends the cookie only over HTTPS.
  • HttpOnly makes it invisible to document.cookie, which limits what an injected script can steal.
  • SameSite=Strict sends the cookie only for same-site requests, Lax also sends it for top-level navigations such as clicking a link, and None (which requires Secure) sends it in all contexts. Browsers treat a missing value as Lax. This reduces cross-site request forgery.
  • The __Host- name prefix forces Secure, Path=/, and no Domain, 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.

javascript
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.