How-To Guide

How to Set Cookies Securely in Web Applications

Set cookies with the right flags: HttpOnly, Secure, SameSite, Path, and Max-Age, and avoid common session-hijacking and CSRF mistakes.

On this page

  1. Introduction
  2. Set the flags that protect the value
  3. Scope and expire deliberately
  4. Serialize values without breaking the grammar
  5. Clear cookies correctly
  6. Verify on the wire and in the browser
  7. Common pitfalls
  8. Conclusion

Introduction

A cookie is the browser’s way of remembering a small piece of state and sending it back on later requests. Session tokens live in cookies, and so do preferences and consent flags. Because the browser attaches cookies automatically, every attribute on the Set-Cookie header is a security decision, not a formatting detail. A session cookie missing HttpOnly can be read by any script that ever achieves cross-site scripting on the origin, and a cookie missing Secure can leak over plaintext requests.

This tutorial walks through the flags that matter, when to use each, how to scope and expire a cookie correctly, and how to serialize values without breaking the header grammar. It then shows how to verify the flags on the wire and how to test that the browser honors them. The examples use Node.js, but the attributes are protocol-level and identical in any framework.

Set the flags that protect the value

HttpOnly prevents JavaScript from reading the cookie through document.cookie. For session identifiers this closes the main exfiltration path of an XSS bug: an injected script still runs, but it cannot simply read and send the session. Secure ensures the browser only transmits the cookie over HTTPS, protecting it from a downgrade or a plaintext request. In production, always set Secure; on localhost during development a browser may permit its absence, but the production configuration must not.

SameSite controls what happens on cross-site requests. Strict sends the cookie only for same-site requests, which blocks CSRF but also breaks arriving via an external link while logged in. Lax, the common default, sends it on top-level navigation but not on cross-site subrequests, balancing usability and safety. None requires Secure and is only for genuinely cross-site cookies, such as those used inside an embedded widget.

function sessionCookie(token, maxAgeSeconds) {
  const parts = [
    'session=' + encodeURIComponent(token),
    'Path=/',
    'HttpOnly',
    'Secure',
    'SameSite=Lax',
    'Max-Age=' + maxAgeSeconds,
  ];
  return parts.join('; ');
}

Scope and expire deliberately

The Domain attribute widens a cookie to subdomains; omitting it makes the cookie host-only, which is safer. A host-only cookie cannot be read or overwritten by a sibling subdomain, so a lower-trust service on the same parent domain cannot tamper with it. For session cookies, omit Domain and rely on the default host-only behavior. The __Host- name prefix enforces this: a cookie named __Host-session must be Secure, host-only, and Path=/, and browsers reject it otherwise, which turns the safe configuration into a guaranteed one.

Always set an explicit Max-Age or Expires so the cookie has a bounded lifetime. A session cookie that never expires survives a browser restart and accumulates on shared machines, widening the window for theft. Tie the cookie lifetime to the server-side session lifetime so an expired cookie and an invalid session do not disagree for long.

import { createServer } from 'node:http';

function login(res, token) {
  res.setHeader('Set-Cookie', [
    '__Host-session=' + encodeURIComponent(token) +
      '; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600',
    '__Host-csrf=' + 'abc123' +
      '; Path=/; Secure; SameSite=Strict; Max-Age=3600',
  ]);
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ ok: true }));
}

Serialize values without breaking the grammar

Cookie values must not contain the separator characters semicolon, comma, whitespace, or control characters. Percent-encode dynamic values before placing them in the header, and validate that a token is a fixed alphabet so encoding is a formality rather than a rescue. Never place raw user input into a cookie value; even with encoding, an oversized value can exceed per-cookie size limits and be dropped.

For anything that carries meaning, sign or encrypt the value rather than storing it in plaintext. A signed cookie lets the server detect tampering; an encrypted cookie hides the content from the user, which matters for flags that should not be user-controllable. Signing is cheaper and sufficient when the content is not secret but must be authentic.

Clear cookies correctly

To remove a cookie, send the same name, Path, and Domain with an empty value and an expiry in the past. A mismatch in any attribute means the browser keeps the original cookie, which is a common bug after a move from a subdomain-scoped cookie to a host-only one. Clear both the session cookie and any related CSRF cookie on logout, and invalidate the server-side session so a copied value is useless even if it lingers in some cache.

Verify on the wire and in the browser

Inspect the raw Set-Cookie headers with curl and confirm every flag. Then load the page in a browser and confirm in devtools that an HttpOnly cookie is absent from document.cookie while still being sent on subsequent requests. Test expiry by setting a short Max-Age and confirming the cookie disappears, and test scope by verifying a host-only cookie is not visible to a subdomain.

curl -sD - -o /dev/null http://localhost:3000/login | grep -i set-cookie
# expect: __Host-session=...; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600

Common pitfalls

Missing HttpOnly or Secure, using SameSite=None without Secure, setting a broad Domain when host-only would do, relying on a session cookie with no Max-Age, and clearing a cookie with mismatched attributes are the mistakes that recur. Each maps to a flag or an attribute rule that a single tested cookie helper can enforce, so the policy is applied consistently instead of re-decided at every call site.

Conclusion

Every Set-Cookie attribute is a security control: HttpOnly blocks script access, Secure blocks plaintext transmission, SameSite blocks cross-site abuse, and an explicit Max-Age bounds the theft window. Prefer host-only cookies and the __Host- prefix, encode and sign values, and clear cookies with exactly matching attributes. Self-check by reading the raw header and asserting each flag, then confirming in a browser that an HttpOnly cookie is invisible to JavaScript but still sent. Consistency across call sites is what makes the policy real.

Sources: MDN: Set-Cookie header, RFC 6265bis: Cookies: HTTP State Management, OWASP: Session management cheat sheet.

FAQ

What does the __Host- prefix guarantee?
A cookie named __Host-... must be set with Secure, without a Domain attribute, and with Path=/. This guarantees the cookie is host-only and cannot be overwritten by a subdomain, which blocks a subdomain-takeover cookie-injection attack.
Is SameSite=Lax safe for login cookies?
Lax is a good default for session cookies: it sends the cookie on top-level navigations but blocks it on cross-site subrequests and most cross-site POSTs, which mitigates CSRF. For sensitive actions, combine it with a CSRF token rather than relying on SameSite alone.

Related Examples