Skip to content

JWT vs Session Cookies in 2026: Stop Getting Auth Wrong

JWT vs session cookies, honestly compared: where to store a JWT, refresh token rotation, revocation, CSRF, mobile clients, and what I ship in 2026.

By Security & Best PracticesUpdated 25 min read

On this page

Every few months I get pulled into an incident that traces back to the same root cause: someone read a tutorial in 2017, learned that JWTs are "stateless and scalable," and built their entire web app's auth around access tokens parked in localStorage. Then a contractor shipped an XSS hole through a markdown renderer, and now an attacker has a token that stays valid for an hour with no way to kill it.

So here is the short version of JWT vs session cookies. For a browser-based web app where your server and your frontend share a site, use an opaque session ID in an HttpOnly, Secure, SameSite cookie, backed by a server-side store. Use JWTs when you genuinely need a token that a different service can verify without calling home: service-to-service calls, short-lived access tokens for mobile and third-party API clients, and edge functions with no route to your session store. And if you are asking where to store a JWT in a browser, the answer is the same place you would store a session ID: an HttpOnly cookie, never localStorage.

This post is for developers and technical founders deciding how auth should work before it gets expensive to change. It covers the real tradeoff, cookie attributes, refresh token rotation, revocation, CSRF, mobile and API clients, and working Next.js and Node code for both approaches, with a decision table at the end.

What each thing actually is

A session cookie carries an opaque random ID. The server generates it, stores the real session data (user ID, roles, expiry) in a server-side store keyed by that ID, and hands the browser a cookie. On every request the browser sends the cookie back, the server looks up the session, and you're authenticated. The ID itself means nothing. It is a pointer into your store.

A JWT is a signed, self-contained token. It carries the claims (user ID, roles, expiry) in its payload, and a signature proves the server issued it. The server doesn't need to store anything: it verifies the signature with a key it already holds. That's the whole pitch, no database lookup per request.

Two clarifications that clear up most of the confusion I see in reviews:

  • "Cookie" is a transport, not a token format. You can put a JWT in a cookie, and you can put an opaque session ID in an Authorization header. The real debate is "server-side state vs self-contained token" and, separately, "cookie vs JavaScript-accessible storage."
  • A JWT is signed, not encrypted. Anyone holding the token can base64-decode the payload and read it. Don't put emails, internal IDs you consider sensitive, or permissions you'd rather not advertise in there.

The difference that matters in practice is this: a session is revocable because the server holds the truth. A JWT is not, because the client holds the truth. Everything else flows from there.

JWT vs session: the real tradeoff is revocation

Here is the scenario that bites teams. A user clicks "log out all devices" after their laptop is stolen. With sessions, you delete the rows and every stolen cookie is dead on the next request. With a stateless JWT, you can't: verification is just math on the signature, and the token stays valid until it expires.

The same applies to the weekly cases in any SaaS: a user is removed from an org, a subscription lapses, an owner is demoted. With sessions, the next request sees the new state. With a JWT embedding role: "owner", the old role works until expiry. If your permissions system reads roles from the token, authorization is wrong by design for that window.

The usual workaround is a token denylist: keep a set of revoked token IDs and check it on every request. Stop and notice what you just did. You added a per-request lookup to kill the one feature JWTs exist to provide. You now have all the operational cost of a session store plus the larger payload and the signing complexity. The OWASP JWT Cheat Sheet says as much: a denylist makes your tokens less stateless, so consider plain server-side sessions instead. If you find yourself building a JWT blocklist, you wanted sessions.

Where to store a JWT (and why not localStorage)

The second disaster is storage. Tutorials tell you to put the JWT in localStorage and attach it with an Authorization: Bearer header. The problem: localStorage is readable by any JavaScript running on your origin. One XSS bug (a vulnerable dependency, an unescaped user string in a template, a compromised npm package) and the attacker reads the token and exfiltrates it. The OWASP HTML5 Security Cheat Sheet is blunt about it: do not store session identifiers in local storage, because the data is always accessible by JavaScript.

A cookie marked HttpOnly is invisible to JavaScript. The same XSS that drains localStorage cannot read an HttpOnly cookie. People counter that XSS means "game over anyway," but that's lazy. With HttpOnly, the attacker is confined to acting through the victim's live browser tab while it stays open; they cannot lift a long-lived bearer token and replay it from their own infrastructure for the next hour. Defense in depth is the whole job.

Here is how the storage options actually rank for a browser app:

StorageReadable by XSSSurvives reloadSent automaticallyVerdict
localStorageYesYesNoDon't, for anything that grants access
sessionStorageYesPer tabNoSame problem, smaller window
In-memory JS variableYes, while the page is openNoNoAcceptable for a short access token if refresh lives in a cookie
HttpOnly cookieNoYesYesThe default for browsers

The in-memory pattern (short access token in a closure, HttpOnly refresh cookie to recover on reload) is reasonable when the API lives on another site. But once you have a refresh cookie, you've already accepted cookies and their CSRF considerations, so ask what the extra moving parts buy you.

Cookies are only safe if you set the attributes correctly. I verified each of these against MDN's Set-Cookie reference and the OWASP Session Management Cheat Sheet:

AttributeWhat it doesWhat I set
HttpOnlyBlocks document.cookie access. The cookie is still sent with fetch requests.Always, for auth cookies
SecureOnly sent over HTTPS (localhost is exempt)Always
SameSite=StrictOnly sent on same-site requests, including not on links clicked from other sitesAdmin panels, banking-grade apps
SameSite=LaxAlso sent on cross-site top-level navigations with safe methods like GET. Not on cross-site POST, fetch, images, or iframes.Most apps, so inbound links keep you logged in
SameSite=NoneSent on all cross-site requests. Requires Secure.Only for genuine cross-site embeds
PathLimits which URL paths receive the cookie. MDN is explicit that it is not a security boundary./, or narrower for refresh cookies
DomainIf set, the cookie goes to that domain and all subdomains. If omitted, host-only.Omit it. Host-only is safer.
Max-Age / ExpiresLifetime. Max-Age wins if both are set. Neither means the cookie dies when the browser closes (session restore can bring it back).Max-Age, matched to the server-side TTL
__Host- prefixBrowser rejects the cookie unless it is Secure, has Path=/, and has no DomainUse it for the session cookie

Two details people miss. First, set SameSite explicitly: MDN notes that when browsers apply Lax by default, they use a looser variant that still sends the cookie on cross-site POSTs within two minutes of it being set. Second, __Host- requires Path=/, so a refresh cookie scoped to /auth/refresh must use the __Secure- prefix instead.

OWASP's own example of a well-formed session cookie is exactly this shape:

Set-Cookie: __Host-SessionID=<random>; Secure; HttpOnly; SameSite=Strict; Path=/

Sessions done right in Node

Here's the shape I use in an Express or Fastify service. The session ID comes from a CSPRNG, the server-side record has both an idle and an absolute expiry, and the ID is regenerated at login to prevent session fixation.

import { randomBytes, createHash } from "node:crypto";
import type { Request, Response } from "express";
import { redis } from "./redis";
 
const IDLE_TTL_S = 60 * 60 * 24;          // 24h of inactivity kills it
const ABSOLUTE_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days, no matter what
const COOKIE = "__Host-sid";
 
// Store a hash of the ID, so a leaked Redis dump isn't a pile of live sessions.
const key = (id: string) => `sess:${createHash("sha256").update(id).digest("hex")}`;
 
export async function createSession(res: Response, userId: string) {
  const id = randomBytes(32).toString("base64url"); // 256 bits
  const now = Date.now();
 
  await redis.set(
    key(id),
    JSON.stringify({ userId, createdAt: now, absoluteExpiry: now + ABSOLUTE_TTL_MS }),
    "EX",
    IDLE_TTL_S,
  );
  await redis.sadd(`user-sessions:${userId}`, key(id));
 
  res.cookie(COOKIE, id, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
    maxAge: ABSOLUTE_TTL_MS, // Express takes milliseconds here
  });
}
 
export async function getSession(req: Request) {
  const id = req.cookies?.[COOKIE];
  if (!id) return null;
 
  const raw = await redis.get(key(id));
  if (!raw) return null;
 
  const session = JSON.parse(raw);
  if (Date.now() > session.absoluteExpiry) {
    await redis.del(key(id));
    return null;
  }
 
  await redis.expire(key(id), IDLE_TTL_S); // sliding idle timeout
  return session;
}
 
export async function logoutEverywhere(userId: string) {
  const keys = await redis.smembers(`user-sessions:${userId}`);
  if (keys.length) await redis.del(...keys);
  await redis.del(`user-sessions:${userId}`);
}

On login, always destroy any existing session and issue a new ID. OWASP's guidance is to renew the session ID after any privilege change: login, password change, role elevation. Revocation is a single DEL, and "log out all devices" is the index set above. That ease is the entire point.

OWASP's minimum is 64 bits of entropy for a session ID, and it recommends at least 128 bits if you generate your own; 32 random bytes is 256. Its suggested idle timeouts are 2 to 5 minutes for high-value apps and 15 to 30 for low-risk ones. Most SaaS products choose longer for usability. That's a product decision, so make it deliberately and require re-authentication for sensitive actions.

You often don't need Redis for this; a Postgres sessions table indexed on the ID hash handles a lot of traffic. More on when Redis is worth it.

Sessions done right in Next.js 16

The same model in the App Router. A Server Action sets the cookie (Next.js only lets you set cookies in Server Functions and Route Handlers, not during rendering), and a small data access function reads it. Note that the Next.js cookies() API is async and takes maxAge in seconds, unlike Express, which takes milliseconds. I've seen that mismatch produce 1,000x lifetimes in code ported between the two.

// lib/session.ts
import "server-only";
import { cookies } from "next/headers";
import { randomBytes, createHash } from "node:crypto";
import { cache } from "react";
import { db } from "@/lib/db";
 
const COOKIE = "__Host-sid";
const TTL_S = 60 * 60 * 24 * 30;
const hash = (id: string) => createHash("sha256").update(id).digest("hex");
 
export async function createSession(userId: string) {
  const id = randomBytes(32).toString("base64url");
  await db.session.create({
    data: { idHash: hash(id), userId, expiresAt: new Date(Date.now() + TTL_S * 1000) },
  });
 
  (await cookies()).set(COOKIE, id, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
    maxAge: TTL_S, // seconds in Next.js
  });
}
 
// cache() dedupes the lookup within a single request
export const getSession = cache(async () => {
  const id = (await cookies()).get(COOKIE)?.value;
  if (!id) return null;
 
  const session = await db.session.findUnique({ where: { idHash: hash(id) } });
  if (!session || session.expiresAt.getTime() < Date.now()) return null;
  return session;
});
 
export async function destroySession() {
  const store = await cookies();
  const id = store.get(COOKIE)?.value;
  if (id) await db.session.deleteMany({ where: { idHash: hash(id) } });
  store.delete(COOKIE);
}
// app/login/actions.ts
"use server";
import { redirect } from "next/navigation";
import { verifyPassword } from "@/lib/auth";
import { createSession, destroySession } from "@/lib/session";
 
export async function login(formData: FormData) {
  const user = await verifyPassword(
    String(formData.get("email")),
    String(formData.get("password")),
  );
  if (!user) return { error: "Invalid email or password" };
 
  await destroySession();        // never reuse a pre-login session ID
  await createSession(user.id);
  redirect("/dashboard");
}

Call getSession() inside every Server Action and data access function, not just in a layout. In Next.js 16, middleware.ts is renamed proxy.ts; it's fine for an optimistic redirect to /login, but it isn't an authorization layer (more in the Server Actions post). If you'd rather not own this code, my WorkOS AuthKit walkthrough shows the hosted route.

CSRF: what changes with cookies vs bearer tokens

The standard objection to cookies is CSRF: a malicious site triggers a request to your API, and the browser helpfully attaches the cookie. Exposure depends on the transport, not the token format. Any cookie-based auth (session ID or JWT) is exposed. A bearer token sent from JavaScript is not, which is the one honest point in its favor, paid for with the XSS exposure above.

SameSite=Lax handles most of it: cookies are withheld on cross-site POST, PUT, and DELETE, which kills the classic form-submission attack. It still permits cookies on top-level GET navigations, so keep state-changing operations off GET (you should anyway). But the OWASP CSRF Prevention Cheat Sheet is explicit that SameSite does not replace a proper CSRF defense in most deployments. It's defense in depth, and it does nothing about sibling subdomains you don't fully control, which count as same-site.

What I layer on top, in order of preference:

  1. Fetch Metadata. Reject state-changing requests where Sec-Fetch-Site is cross-site. OWASP recommends falling back to Origin and Referer checks for browsers that don't send it.
  2. Synchronizer token for stateful apps: a random token stored in the session and required in a form field or header.
  3. Signed double-submit cookie when you have no server-side state: an HMAC of the session value, sent back in a header. OWASP marks the naive, unsigned variant as discouraged.
  4. A required custom header like X-CSRF-Token on JSON APIs, which forces a CORS preflight for cross-origin callers.

Next.js Server Actions get some of this for free: they only accept POST, and Next.js compares the Origin header to the Host header and aborts on a mismatch. Your own Route Handlers don't get that check, so add it. If CORS and CSRF still blur together for you, I wrote a whole post on CORS, CSRF, and the same-origin policy.

When JWTs actually earn their place

I'm not anti-JWT. They're the right tool when statelessness is a genuine requirement and the lifetime is short:

  • Service-to-service auth. Service A calls Service B, and B verifies the signature without a call back to an auth server. The token lives seconds to minutes; revocation is irrelevant at that timescale.
  • Short-lived access tokens with a refresh flow. Issue a 5 to 15 minute access token. Its short life is the revocation strategy: worst case, the attacker has a few minutes.
  • Edge or serverless auth where the function has no connection to a central session store and the latency of a lookup per request is unacceptable.

The thread connecting all of these: short lifetime. A JWT you have to revoke is a JWT you've mis-scoped.

When you use them, follow the OWASP JWT Cheat Sheet: reject alg: none, hardcode the accepted algorithm, never mix MAC and public-key algorithms in one validation path, and generate HMAC secrets with a CSPRNG at the hash's output size (256 bits for HS256). With several verifying services, prefer ES256 or EdDSA so only the issuer holds the signing key.

Refresh token rotation with reuse detection

For apps that need tokens but want safe storage, here's the pattern I deploy: a short-lived JWT access token plus a rotating refresh token, both in HttpOnly cookies, with the refresh side backed by a server-side store. The access token stays stateless for nearly every request; the refresh endpoint is the one place you pay for a stateful lookup, and it's where revocation lives.

Rotation means every refresh returns a new refresh token and invalidates the old one. Reuse detection is the part that makes rotation worth doing. RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025, requires refresh tokens for public clients to be either sender-constrained or rotated. It describes the logic plainly: if an attacker and the legitimate client both hold the same refresh token, one of them will eventually present one that has already been used. The server can't tell which party is which, so it revokes the whole chain. Both get logged out, and the attacker's copy dies.

Here's an implementation with token families:

// auth/tokens.ts
import { SignJWT, jwtVerify } from "jose";
import { randomBytes, createHash } from "node:crypto";
import { redis } from "./redis";
 
const KEY = new TextEncoder().encode(process.env.JWT_SECRET!); // 32+ random bytes
const ISSUER = "https://api.example.com";
const REFRESH_TTL_S = 60 * 60 * 24 * 30;
const sha = (s: string) => createHash("sha256").update(s).digest("hex");
 
export async function issueAccessToken(userId: string, familyId: string) {
  return new SignJWT({ sid: familyId })
    .setProtectedHeader({ alg: "HS256" })
    .setSubject(userId)
    .setIssuer(ISSUER)
    .setIssuedAt()
    .setExpirationTime("10m") // short life IS the revocation strategy
    .sign(KEY);
}
 
export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, KEY, {
    issuer: ISSUER,
    algorithms: ["HS256"], // pinned; never trust the header's alg
  });
  return payload;
}
 
export async function startFamily(userId: string) {
  const familyId = randomBytes(16).toString("base64url");
  await redis.set(`rtfam:${familyId}`, userId, "EX", REFRESH_TTL_S);
  await redis.sadd(`user-families:${userId}`, familyId);
  return { familyId, refreshToken: await mintRefresh(familyId, userId) };
}
 
async function mintRefresh(familyId: string, userId: string) {
  const token = randomBytes(32).toString("base64url");
  await redis.set(
    `rt:${sha(token)}`,
    JSON.stringify({ familyId, userId, used: false }),
    "EX",
    REFRESH_TTL_S,
  );
  return token;
}
 
export async function rotate(presented: string) {
  const raw = await redis.get(`rt:${sha(presented)}`);
  if (!raw) throw new Error("invalid refresh token");
 
  const rec = JSON.parse(raw);
  const familyAlive = await redis.exists(`rtfam:${rec.familyId}`);
  if (!familyAlive) throw new Error("family revoked");
 
  if (rec.used) {
    // Someone presented a token that was already rotated. That's theft
    // (or a badly behaved client). Kill the whole family.
    await redis.del(`rtfam:${rec.familyId}`);
    throw new Error("refresh token reuse detected");
  }
 
  // Mark used rather than delete, so a replay is recognisable later.
  await redis.set(`rt:${sha(presented)}`, JSON.stringify({ ...rec, used: true }), "KEEPTTL");
 
  return {
    accessToken: await issueAccessToken(rec.userId, rec.familyId),
    refreshToken: await mintRefresh(rec.familyId, rec.userId),
  };
}

Both tokens go out as cookies, never touched by JavaScript:

const base = { httpOnly: true, secure: true, sameSite: "strict" as const };
 
res.cookie("__Host-access", accessToken, { ...base, path: "/", maxAge: 10 * 60 * 1000 });
// __Host- requires Path=/, so the path-scoped refresh cookie uses __Secure-
res.cookie("__Secure-refresh", refreshToken, {
  ...base,
  path: "/auth/refresh",
  maxAge: 30 * 864e5,
});

Three production details that tutorials skip:

  • Concurrent refreshes. Two tabs refreshing at once send the same token; the second looks like reuse and logs the user out. Serialize refreshes on the client, or allow a grace window of a few seconds. Keep it tiny, since it's also a window for an attacker.
  • Get the read-modify-write atomic. The check-then-mark in rotate above is two Redis calls; under load, wrap it in a Lua script or WATCH/MULTI (or a Postgres row lock) so two concurrent requests can't both see used: false.
  • Store hashes, not tokens. If your Redis or database leaks, hashed refresh tokens are useless to the attacker.

Revocation strategies, ranked by cost

Once access tokens are JWTs, you need an answer for "kill this user's access right now." Here's what's available, roughly from cheapest to most expensive:

  1. Short expiry and do nothing else. Revoke the refresh family; the access token dies within its 5 to 15 minute lifetime. For most products, that's acceptable, and it's the strategy RFC 9700 and OWASP both lean on.
  2. Session-bound tokens. Include a session or family ID (the sid claim above) and check it against a small, cached set of revoked families. It's a lookup, but a cheap one that you can cache at the edge for a few seconds.
  3. Per-user "valid after" timestamp. Store tokensValidAfter on the user. Reject any token whose iat is earlier. One key per user, and "log out everywhere" becomes a single write.
  4. jti denylist. Store revoked token IDs until their natural expiry. OWASP recommends keying it on jti and iss, not on the raw token or its hash, because malleable encodings can slip past a hash-based list.
  5. Rotate the signing key. The nuclear option. Every token for every user dies. Keep a key ID (kid) in the header and a rotation runbook so this is a deploy, not an outage.

Notice that options 2 to 4 all reintroduce a lookup. That's fine. Just be honest that your tokens are no longer stateless, and ask again whether a session would have been simpler.

Mobile apps, SPAs on other domains, and API clients

The cookie default assumes a browser and a same-site backend. Here's what changes outside that.

Native mobile apps. Cookies work in native HTTP clients, but there's no HttpOnly protection worth speaking of and no browser enforcing SameSite. Tokens are the natural fit here. Do login with OAuth 2.0 Authorization Code plus PKCE through the system browser, as RFC 8252 (OAuth for Native Apps) requires, not an embedded webview. Keep the refresh token in the platform's secure storage (iOS Keychain, Android Keystore-backed storage), keep the access token in memory, and rotate refresh tokens with reuse detection, since a mobile app is a public client under RFC 9700.

SPAs on a different site from the API. If your frontend is app.example.com and your API is api.example.com, that's same-site, and cookies work fine with SameSite=Lax. If the API is on a different registrable domain entirely, third-party cookie restrictions will hurt you. The clean fix is a backend-for-frontend (BFF): a thin server on the frontend's own domain holds the tokens and sets a first-party session cookie. The browser never sees a token at all. I default to this for any SPA that talks to a third-party identity provider.

Third-party API consumers. Server-to-server integrations should use API keys (hashed at rest, scoped, revocable) or the OAuth client credentials flow issuing short-lived JWTs. Neither involves cookies. Pair them with rate limiting per key and store the secrets like secrets, which I cover in secrets management.

JWT access tokens in Next.js 16

If you do go hybrid, the Next.js side reads the access cookie, verifies it with jose, and refreshes when it has expired. proxy.ts (the Next.js 16 name for middleware, now on the Node.js runtime by default) is a good place for the optimistic check, since signature verification needs no database:

// proxy.ts
import { NextResponse, type NextRequest } from "next/server";
import { jwtVerify } from "jose";
 
const KEY = new TextEncoder().encode(process.env.JWT_SECRET!);
 
export async function proxy(req: NextRequest) {
  const token = req.cookies.get("__Host-access")?.value;
 
  if (token) {
    try {
      await jwtVerify(token, KEY, { algorithms: ["HS256"], issuer: "https://api.example.com" });
      return NextResponse.next();
    } catch {
      // expired or invalid: fall through to refresh
    }
  }
 
  const url = new URL("/auth/refresh", req.url);
  url.searchParams.set("next", req.nextUrl.pathname);
  return NextResponse.redirect(url);
}
 
export const config = { matcher: ["/dashboard/:path*", "/settings/:path*"] };

The /auth/refresh Route Handler calls rotate(), sets both cookies, and redirects back. As with sessions, verify again in every Server Action; the proxy check is UX, the data layer is the boundary. If your token embeds roles, re-check sensitive actions (billing, ownership transfer) against the database. Ten minutes of stale authorization is fine for a dashboard, not for wiring money.

The decision, side by side

ConcernSession cookiesStateless JWTHybrid (JWT + rotating refresh)
RevocationInstant (delete the row)Impossible without a denylistAccess expires fast; refresh revocable
Per-request store hitYesNoNo (only on refresh)
Storage safety in browsersHttpOnly cookieFootgun if localStorageHttpOnly cookies
CSRF exposureYes, mitigate with SameSite plus a token or Fetch MetadataNone if Bearer headerYes, same mitigations
Stale roles/permissionsNeverUntil expiryUp to access token lifetime
Horizontal scaleNeeds shared storeTrivialRefresh needs shared store
Mobile / native clientsAwkwardNatural fitNatural fit
Operational complexityLowLow until you need revocationHighest

And the shorter version, by situation:

Your situationWhat I'd use
Server-rendered app or Next.js on one domainOpaque session cookie
SPA plus API on the same siteOpaque session cookie
SPA plus API on different sites, or third-party IdPBFF holding tokens, session cookie to the browser
Native mobile appOAuth Code + PKCE, short JWT access token, rotating refresh token in secure storage
Public API for other companiesScoped API keys or client credentials
Internal service-to-serviceShort-lived JWTs, asymmetric keys
Edge functions with no store accessShort JWT access token, revocable refresh

My default and the checklist

Most interactive web apps should default to opaque session cookies backed by Redis or Postgres. They're simpler, instantly revocable, and safe by construction with the right attributes. Reach for the hybrid only when you have a real mobile client or a native API consumer that needs tokens, or genuine edge-auth latency constraints. Reach for bare stateless JWTs only for short-lived service-to-service calls. Auth is also one of the areas I check first when I audit an app against the OWASP Top 10, because it's where small shortcuts become breaches.

Before you ship auth, run this list:

  • Auth cookies are HttpOnly, Secure, explicit SameSite, and __Host- prefixed where possible.
  • No token, session ID, or credential lives in localStorage or sessionStorage.
  • The session ID is regenerated at login and on privilege changes.
  • Logout invalidates server-side state, not just the client cookie.
  • "Log out all devices" works. If it can't, you don't have real revocation.
  • State-changing endpoints are POST/PUT/PATCH/DELETE, never GET.
  • CSRF is handled: SameSite plus Fetch Metadata, Origin checks, or a token.
  • If you use JWTs: algorithm pinned, issuer and audience checked, lifetime in minutes.
  • Refresh tokens rotate on use, are stored hashed, and reuse kills the family.
  • Session IDs and refresh tokens come from a CSPRNG (128+ bits).
  • Sensitive actions re-check permissions against the database, not just token claims.

If you can't tick "log out all devices" honestly, you don't have an auth system. You have a trust-the-client system with extra steps.

Frequently asked questions

Is JWT more secure than session cookies?

No. Neither format is inherently more secure; what matters is where the credential is stored and whether you can revoke it. A session ID in an HttpOnly cookie is generally safer for browser apps than a JWT in localStorage, because XSS can't read it and you can kill it instantly. A JWT in an HttpOnly cookie with a short lifetime is roughly as safe, just more complex.

Where should I store a JWT in the browser?

In an HttpOnly, Secure, SameSite cookie, set by your server. If you can't use cookies because the API is on another site, keep a short-lived access token in memory and put the refresh token in an HttpOnly cookie, or use a backend-for-frontend so the browser never holds tokens. Avoid localStorage and sessionStorage for anything that grants access.

Can you revoke a JWT?

Not directly, because verification doesn't consult the server. In practice you revoke by keeping access tokens short-lived and revoking the refresh token, or by checking a session ID, a per-user "valid after" timestamp, or a jti denylist on each request. All of the latter reintroduce a lookup, which is why sessions are usually the simpler choice for web apps.

Do I still need CSRF protection with SameSite cookies?

For anything sensitive, yes. SameSite=Lax blocks the classic cross-site form POST, but OWASP treats it as defense in depth rather than a full CSRF defense, partly because sibling subdomains count as same-site. Add a Fetch Metadata check on Sec-Fetch-Site (with an Origin fallback) or a CSRF token on state-changing requests.

What is refresh token rotation?

Every time a client uses a refresh token, the server issues a new one and invalidates the old one. If an invalidated token is ever presented again, the server assumes it was stolen and revokes the whole token family, logging out both the attacker and the user. RFC 9700 requires rotation or sender-constrained tokens for public clients like SPAs and mobile apps.

Should a mobile app use sessions or JWTs?

Usually tokens: a short-lived access token plus a rotating refresh token, obtained via OAuth Authorization Code with PKCE through the system browser. Store the refresh token in the iOS Keychain or Android Keystore-backed storage. The browser-specific protections that make cookies attractive (HttpOnly, SameSite) don't apply in a native HTTP client.

Working with me

Auth is cheap to get right on day one and painful to retrofit once you have users, mobile clients, and an enterprise customer asking about session revocation. If you're designing auth for a new product, or you've inherited one with tokens in localStorage and no way to log anyone out, that's the kind of backend work I do, often as part of building a SaaS product end to end. Get in touch and tell me what you're running.