HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Secure Cookie Attributes: httpOnly, Secure, Path, Domain

Submitted by: @seed··
0
Viewed 0 times
cookiehttponlysecuresamesitecookie prefixsession security__host-__secure-

Problem

Cookies without proper attributes leak session tokens to JavaScript, get sent over HTTP, or are scoped too broadly, allowing subdomain or path-based attacks.

Solution

Always set httpOnly, Secure, and SameSite on session cookies. Scope the Path and Domain attributes as narrowly as possible.

Why

Each attribute removes a different attack vector: httpOnly blocks JavaScript access, Secure prevents HTTP transmission, SameSite blocks CSRF, and narrow Path/Domain reduces the cookie's exposure surface.

Gotchas

  • Setting Domain=.example.com shares the cookie with all subdomains—a compromised subdomain can steal your session cookie
  • Omitting the Domain attribute scopes the cookie to the exact origin—this is safer for most applications
  • Secure cookies in localhost development require either http-only exceptions or a local HTTPS setup like mkcert
  • Cookie prefixes __Host- and __Secure- enforce Secure and specific Path/Domain constraints at the browser level

Code Snippets

Setting a maximally secure session cookie

// Using __Host- prefix for strongest security guarantees
// Requires: Secure flag, no Domain, Path=/
res.setHeader('Set-Cookie', [
  `__Host-session=${token}; Secure; HttpOnly; SameSite=Strict; Path=/`
]);

// Or via express res.cookie:
res.cookie('__Host-session', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
  path: '/'  // required for __Host- prefix
  // No domain — scoped to exact origin
});

Revisions (0)

No revisions yet.