Session in httpOnly cookie or JWT in localStorage: what to choose for a web application
The question is posed inaccurately
The cookie vs JWT debate confuses two independent solutions:
- 1.Where the client stores the token: httpOnly cookie, which the browser sends itself, or
localStorage, from where JavaScript reads it and puts it in theAuthorizationheader. - 2.What is this token: an opaque session identifier by which the server finds an entry in the database, or a self-sufficient signed JWT.
The JWT can be stored in an httpOnly cookie and the session ID in localStorage. Therefore, we will analyze each solution separately.
Where to store: XSS consequences
If someone else's script was executed on the page (vulnerable dependency, unescaped user input, compromised analytics script):
- Token in `localStorage` the script will read and send to its server. The attacker uses the session from his machine while the token is valid, even after the victim has closed the tab.
- The token in the httpOnly cookie cannot be read by the script. It can send requests on behalf of the user while the page is open - XSS remains a serious vulnerability. But you cannot steal a session and take it with you.
The difference is not whether the cookie "protects against XSS" (it doesn't), but the extent of the damage. For a web application where the frontend and API are on the same site, this solves the issue in favor of cookies.
Cookie price: CSRF
The browser sends cookies automatically, including to requests initiated by another site. Protection in several layers:
SameSite=Lax(default in Chromium browsers, but set explicitly) does not send cookies with cross-site POST requests.- For modifying requests, the server checks the
Originheader and rejects requests from a foreign origin. - State changes - only using POST/PUT/PATCH/DELETE methods, never GET.
Server Actions in Next.js check Origin themselves; For your own Route Handlers, you write the check.
What to store: session recall
The server verifies the signed JWT without accessing the database. The downside: it cannot be revoked before the expiration date. The user clicked “log out on all devices”, the administrator blocked the account, the stolen token was detected - JWT continues to work. Workarounds (short lifetime plus refresh token, revoked list) return access to the storage, for the sake of which the JWT was chosen to be missing.
Server session is an entry in a table. Revocation - deleting a line, effective immediately. One access to the database per request is invisible for most applications, and is cached if necessary.
Implementation of a server session
CREATE TABLE sessions ( id_hash bytea PRIMARY KEY, user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), user_agent text ); CREATE INDEX sessions_user_idx ON sessions (user_id);
// lib/auth/sessions.ts
import "server-only";
import { createHash, randomBytes } from "node:crypto";
import { cookies } from "next/headers";
import { db } from "@/lib/db";
const COOKIE = "__Host-session";
const TTL_DAYS = 30;
const sha256 = (s: string) => createHash("sha256").update(s).digest();
export async function createSession(userId: string, userAgent?: string) {
const token = randomBytes(32).toString("base64url");
const expires = new Date(Date.now() + TTL_DAYS * 86_400_000);
await db.query(
"INSERT INTO sessions (id_hash, user_id, expires_at, user_agent) VALUES ($1, $2, $3, $4)",
[sha256(token), userId, expires, userAgent?.slice(0, 200) ?? null]
);
const jar = await cookies();
jar.set(COOKIE, token, {
httpOnly: true, secure: true, sameSite: "lax", path: "/", expires,
});
}
export async function currentUserId(): Promise<string | null> {
const token = (await cookies()).get(COOKIE)?.value;
if (!token) return null;
const { rows } = await db.query(
"SELECT user_id FROM sessions WHERE id_hash = $1 AND expires_at > now()",
[sha256(token)]
);
return rows[0]?.user_id ?? null;
}
export async function destroySession() {
const jar = await cookies();
const token = jar.get(COOKIE)?.value;
if (token) await db.query("DELETE FROM sessions WHERE id_hash = $1", [sha256(token)]);
jar.set(COOKIE, "", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 0 });
}Key details:
- The database has a hash, not a token. Leaking a dump or read-only access to the table does not provide ready-made sessions.
- 32 random bytes from a cryptographic generator - brute force is not possible, no signature required.
- New session upon login, rather than increasing the rights of the old one. Otherwise, session fixation is possible: the attacker slips his identifier to the victim before logging in.
- `cookies()` is asynchronous in Next.js 15, hence
await. You can set cookies in Server Actions and Route Handlers, but not when rendering the server component.
“Log out on all devices” - DELETE FROM sessions WHERE user_id = $1. A list of active sessions with user_agent and date is a free bonus of this scheme.
When the token in the header is justified
- Mobile application or CLI. Cookies are inconvenient there, the token is stored in the platform’s secure storage (Keychain, Keystore), and not in
localStorage. - API for third-party clients. They are issued separate keys or OAuth tokens with limited rights.
- Inter-service calls. Short-lived JWT between your services is convenient precisely because it is verified without a common base.
Frequent errors
- Refresh token in
localStoragewhen the access token is short-lived. A stolen refresh token gives long-term access - all the short-term benefits are lost. Domain=.example.comfor session cookies unnecessarily. Any subdomain, including a vulnerable landing page, will receive it. The__Host-prefix disables theDomainattribute and closes this option.- Checking
expfor JWT without signature verification or with the algorithm from the token header. Record the algorithm on the server.
Summary
For a web application with its own backend: opaque identifier in httpOnly cookie, session records in the database, SameSite=Lax and check Origin. JWT and header Authorization - for non-browser clients and for communication between services.