How stateless JWTs and server-side sessions differ on revocation, storage, size and scaling, where each one fits, and how both look as an auth handler in a TypeScript backend.

The JWT vs session question usually arrives as "should my API be stateless?", and the practical answer is that most APIs are not, because the first time a user clicks "log out of all devices" or an admin disables an account, a stateless token keeps working until it expires.
JWTs earn their place when someone else issues the token or when many services must check it without a shared store; sessions are simpler and safer for a web app talking to its own backend.
This guide compares the two on the things that decide it, then shows each as an auth handler.
A session is a pointer to server state, so ending it is deleting the row; the next request fails. A JWT carries its own claims and stays valid until exp. Revoking one requires a deny list of token IDs or a per-user version number that every request checks, which is a database or cache lookup on every call, the cost JWTs were supposed to remove. The usual compromise is short-lived access tokens (5 to 15 minutes) plus a refresh token stored server-side, so revocation takes effect at the next refresh rather than instantly.
Where the client keeps the credential matters more than its format. A token in localStorage can be read by any script that runs on the page, so one XSS bug leaks it. An httpOnly cookie cannot be read by JavaScript, but the browser sends it automatically, which brings CSRF into play; SameSite=Lax or Strict plus a CSRF token on state-changing requests handles that. The OWASP Session Management Cheat Sheet covers cookie attributes, and the JWT cheat sheet covers algorithm pinning and token sidejacking. You can put a JWT in an httpOnly cookie too, which gives it the cookie's protections but none of the session's revocability.
A session ID is a few dozen bytes; a JWT with a handful of claims is often over 500 bytes and is sent on every request, which matters for mobile clients and for cookies near the 4 KB limit. The scaling argument for JWTs, no shared store, mostly applies across organizations or many independent services. A single backend already has a database, and a session lookup by primary key, optionally cached in Redis, is rarely the bottleneck.
JWTs fit when the token comes from someone else: an identity provider such as Auth0, Clerk, Cognito or Firebase issues it, and your API verifies the signature against the provider's JWKS without calling the provider on each request. They also fit service-to-service calls where the caller's identity has to cross trust boundaries. Pin the algorithm, validate iss, aud and exp, and keep lifetimes short.
import { createRemoteJWKSet, jwtVerify } from "jose";
// JWT from an identity provider: verify signature and claims, no lookup.
const jwks = createRemoteJWKSet(new URL("https://auth.example.com/.well-known/jwks.json"));
export async function verifyJwt(token: string) {
const { payload } = await jwtVerify(token, jwks, {
issuer: "https://auth.example.com/",
audience: "api.example.com",
algorithms: ["RS256"],
});
return payload.sub!;
}
// Session: look up the random ID, reject expired or revoked sessions.
export async function verifySession(sessionId: string) {
const { rows } = await pool.query(
"SELECT user_id FROM sessions WHERE id = $1 AND expires_at > now() AND revoked_at IS NULL",
[sessionId],
);
return rows[0]?.user_id as string | undefined;
}
jose caches the provider's keys and refetches them on rotation. Each check still has to be wired into middleware and applied to every protected route.
Encore is a backend framework with built-in infrastructure for TypeScript and Go, and either approach becomes one auth handler that runs at the gateway before any endpoint marked auth: true. Auth parameters can be headers or cookies, so a session cookie and a bearer JWT can be accepted side by side. encore run starts Postgres locally for the session table, and on deploy to your own AWS or GCP account Encore provisions RDS or Cloud SQL and provisions an IAM role for the service, or a service account on GCP.
Run in your terminal to get started locally.
// auth/auth.ts
import { api, APIError, Cookie, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { randomBytes } from "node:crypto";
import { verifyJwt } from "./jwt"; // the jose check from above
const db = new SQLDatabase("auth", { migrations: "./migrations" });
interface AuthParams {
session?: Cookie<"session">;
authorization?: Header<"Authorization">;
}
interface AuthData {
userID: string;
}
export const auth = authHandler<AuthParams, AuthData>(async ({ session, authorization }) => {
if (session) {
const row = await db.queryRow<{ user_id: string }>`
SELECT user_id FROM sessions
WHERE id = ${session.value} AND expires_at > now() AND revoked_at IS NULL`;
if (row) return { userID: row.user_id };
}
if (authorization?.startsWith("Bearer ")) {
return { userID: await verifyJwt(authorization.slice(7)) };
}
throw APIError.unauthenticated("not signed in");
});
export const gateway = new Gateway({ authHandler: auth });
export const login = api(
{ expose: true, method: "POST", path: "/login" },
async (p: { email: string; password: string }): Promise<{ session: Cookie<"session"> }> => {
const userId = await checkPassword(p.email, p.password); // your password check
const id = randomBytes(32).toString("base64url");
await db.exec`
INSERT INTO sessions (id, user_id, expires_at) VALUES (${id}, ${userId}, now() + interval '7 days')`;
return {
session: { value: id, httpOnly: true, secure: true, sameSite: "Lax", maxAge: 7 * 24 * 3600 },
};
},
);
Logout and "sign out everywhere" are UPDATE sessions SET revoked_at = now() for one row or for every row of a user, effective on the next request. Requests from an identity provider's SPA or a partner backend send a bearer JWT and go through the second branch. Every endpoint reads the same getAuthData() no matter which credential was used, and the auth handler call appears in each trace in the local development dashboard.
A coding agent adding a protected endpoint sets auth: true and reads getAuthData(); the choice between cookie sessions and JWTs stays in one file.
Best fit: TypeScript or Go backends that serve their own web app with revocable cookie sessions and also accept JWTs from an identity provider or partner, in their own AWS or GCP account.
For a web app and its own API, use sessions in an httpOnly cookie and store them in Postgres, with Redis in front only if lookups show up in your traces. For tokens issued by an identity provider, verify JWTs against its JWKS and keep them short-lived. If you need both, accept both in one auth layer instead of building two.
Use server-side sessions in an httpOnly cookie for a first-party web app talking to its own backend, because logout and revocation are immediate and the token never reaches JavaScript. Use JWTs when another party issues the token, such as an identity provider, or when several services must verify a caller without a shared session store, and keep their lifetime short.
No. A signed JWT stays valid until its exp claim, so revoking one means keeping a deny list or a per-user token version that every request checks, which reintroduces the server-side lookup JWTs were meant to avoid. Short-lived access tokens with a revocable refresh token are the common compromise.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.