Description
Without HttpOnly, page scripts can read an authentication cookie or session token through document.cookie. An XSS flaw may expose those values. HttpOnly protects the cookie value from scripts. XSS and a compromised browser require separate defenses.
Potential impact
Someone who obtains a session cookie may impersonate the user and access sensitive information. Long-lived sessions or weak reauthentication for sensitive actions can allow account takeover.
Remediation
Prefer HttpOnly cookies to local storage for session IDs and access tokens. Set the attribute where the application issues the cookie.
- In Express, use
res.cookie(name, value, { httpOnly: true, secure: true, sameSite: 'Strict' }). - In Koa,
httpOnlydefaults totrue. Check for overrides that sethttpOnly: false. - In a Next.js Server Function or Route Handler, use
(await cookies()).set(name, value, { httpOnly: true, secure: true, sameSite: 'strict' }). - If you write the Node.js
Set-Cookieheader directly, include; HttpOnly.
Use Secure for HTTPS-only transmission. Choose SameSite (Strict or Lax), Path, Domain, and expiration (Max-Age or Expires) for the cookie’s intended use. Where needed, store sessions on the server and rotate session IDs or tokens. Address XSS with input validation, context-appropriate output encoding, and a Content Security Policy (CSP).
Examples
Before
// Before: HttpOnly is missing.
const crypto = require("crypto");
const express = require("express");
const app = express();
app.get("/signin", (req, res) => {
const token = crypto.randomBytes(32).toString("base64url");
// Missing HttpOnly allows document.cookie to read the value.
res.cookie("auth", token, {
secure: true,
sameSite: "Lax",
path: "/",
});
res.send("signed in");
});
app.listen(3000);
After
// After: include HttpOnly.
const crypto = require("crypto");
const express = require("express");
const app = express();
app.get("/signin", (req, res) => {
const token = crypto.randomBytes(32).toString("base64url");
// Set HttpOnly, Secure, and SameSite.
res.cookie("auth", token, {
httpOnly: true,
secure: true,
sameSite: "Strict",
path: "/",
maxAge: 10 * 60 * 1000, // 10 minutes
});
res.send("signed in");
});
app.listen(3000);
Explanation:
- Before: Browser JavaScript can read the cookie through
document.cookie. XSS may expose it and allow session hijacking. - After: HttpOnly blocks script access to the cookie value. Secure and SameSite add transport and CSRF protections. XSS still requires separate prevention.