Square CloudSquare Cloud

JWT vs cookie sessions: which to use for login

With a cookie session, the server keeps the state and the browser carries only an ID; a JWT carries the signed data itself. For a website login, sessions are usually simpler to revoke; JWTs fit better between services and APIs.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Understand where the login state lives in each approach
  • Compare logout, revocation, CSRF and XSS between sessions and JWTs
  • Pick an approach for one or several instances behind a load balancer
On this page

Once a user types the right password (checked against a slow hash), the server has to remember that on the following requests, because HTTP keeps no memory between one request and the next. There are two popular ways: keep the state on the server and hand the browser only an identifier in a cookie, or hand it a signed token, the JWT, that carries the data with it.

The difference is where the state lives, and that changes logout, the attacks to defend against and what happens with more than one instance.

At login, the server generates a random identifier, writes the session data (such as the user ID) to a store (a database or Redis) and sends the identifier in a cookie. On every request the browser sends the cookie back on its own, and the server looks up the session by it.

OWASP asks for at least 64 bits of entropy from a cryptographically secure random generator, a new ID at every login (against session fixation) and server-side invalidation at logout. The cookie should carry three attributes:

  • HttpOnly: the page's JavaScript cannot read the cookie, which limits the damage of an XSS.
  • Secure: the cookie only travels over HTTPS.
  • SameSite=Strict (OWASP's preference) or Lax: the browser does not send the cookie on requests triggered by other sites (with Lax, only on top-level navigations with a safe method, like clicking a link).

An example with Express 5, express-session and the Redis store from connect-redis:

js
// npm install express@5 express-session connect-redis redis
import { RedisStore } from "connect-redis";
import express from "express";
import session from "express-session";
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
redis.on("error", (err) => console.error("Redis:", err.message));
await redis.connect();

// Example: in production, load the user from the database and verify the password hash
async function checkCredentials(email, password) {
  return email === "ana@example.com" && password === "example passphrase" ? { id: "u1" } : null;
}

const app = express();
app.set("trust proxy", 1); // HTTPS ends at the proxy: without this, the Secure cookie is not sent
app.use(express.json());
app.use(
  session({
    store: new RedisStore({ client: redis, prefix: "sess:" }),
    secret: process.env.SESSION_SECRET,
    name: "sid",
    resave: false,
    saveUninitialized: false,
    cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 8 * 60 * 60 * 1000 },
  }),
);

app.post("/login", async (req, res, next) => {
  const user = await checkCredentials(req.body?.email, req.body?.password);
  if (!user) return res.status(401).json({ error: "Invalid email or password" });
  // a new ID at every login, against session fixation
  req.session.regenerate((err) => {
    if (err) return next(err);
    req.session.userId = user.id;
    res.json({ ok: true });
  });
});

app.get("/me", (req, res) => {
  if (!req.session.userId) return res.sendStatus(401);
  res.json({ id: req.session.userId });
});

app.post("/logout", (req, res, next) => {
  req.session.destroy((err) => {
    if (err) return next(err);
    res.clearCookie("sid").sendStatus(204);
  });
});

app.listen(Number(process.env.PORT) || 3000);

destroy deletes the session from Redis: the old cookie stops working, even if someone copied it. express-session's default store, MemoryStore, is not for production: its own documentation warns that it leaks memory and does not scale past a single process.

How does a JWT work?#

A JWT (RFC 7519) has three Base64url parts separated by dots: header, payload and signature. The payload carries the claims, such as sub (who the user is), iat (when it was issued) and exp (when it expires). The server signs it with a secret (HS256) or a private key (RS256, ES256) and later verifies the signature without looking anything up.

Two precautions come from RFC 8725, the JWT best practices. First, pin the accepted algorithms on verification instead of trusting the token's alg field: a parser that accepts "alg": "none" accepts forged tokens. Second, an HS256 key needs real entropy: a memorable password falls to an offline dictionary attack. And the payload is only encoded, not encrypted (here is the difference): anyone with the token reads all of it.

An example with the jose library, with a short access token and a refresh token in a cookie:

js
// npm install express@5 jose cookie-parser
import crypto from "node:crypto";
import cookieParser from "cookie-parser";
import express from "express";
import { SignJWT, jwtVerify } from "jose";

const secret = new TextEncoder().encode(process.env.JWT_SECRET); // 32 random bytes or more

// Example: in production, load the user from the database and verify the password hash
async function checkCredentials(email, password) {
  return email === "ana@example.com" && password === "example passphrase" ? { id: "u1" } : null;
}

// Valid refresh tokens. In production: Redis or a database, storing the token's hash
const refreshTokens = new Map();

async function issueTokens(res, userId) {
  const refresh = crypto.randomBytes(32).toString("base64url");
  refreshTokens.set(refresh, userId);
  res.cookie("refresh", refresh, {
    httpOnly: true,
    secure: true,
    sameSite: "strict",
    path: "/auth",
    maxAge: 7 * 24 * 60 * 60 * 1000,
  });
  const accessToken = await new SignJWT({})
    .setProtectedHeader({ alg: "HS256" })
    .setSubject(userId)
    .setIssuedAt()
    .setExpirationTime("15m") // short: it cannot be revoked before that
    .sign(secret);
  res.json({ accessToken }); // the frontend keeps it in memory, not in localStorage
}

const app = express();
app.set("trust proxy", 1);
app.use(express.json());
app.use(cookieParser());

app.post("/auth/login", async (req, res) => {
  const user = await checkCredentials(req.body?.email, req.body?.password);
  if (!user) return res.status(401).json({ error: "Invalid email or password" });
  await issueTokens(res, user.id);
});

app.post("/auth/refresh", async (req, res) => {
  const old = req.cookies.refresh;
  const userId = refreshTokens.get(old);
  if (!userId) return res.sendStatus(401);
  refreshTokens.delete(old); // rotation: each refresh token works once
  await issueTokens(res, userId);
});

app.post("/auth/logout", (req, res) => {
  refreshTokens.delete(req.cookies.refresh);
  res.clearCookie("refresh", { path: "/auth" }).sendStatus(204);
  // an access token already issued stays valid until it expires
});

app.get("/me", async (req, res) => {
  const token = req.get("Authorization")?.replace(/^Bearer /, "") ?? "";
  try {
    const { payload } = await jwtVerify(token, secret, { algorithms: ["HS256"] });
    res.json({ id: payload.sub });
  } catch {
    res.sendStatus(401);
  }
});

app.listen(Number(process.env.PORT) || 3000);

The refresh token is opaque, stored on the server and delivered in an HttpOnly cookie scoped to /auth. Notice that a real logout required storing state on the server: that is the price of revocation.

What are the differences, side by side?#

Cookie session JWT
Where state lives On the server (database, Redis) In the token itself, on the client
What travels A random ID The signed claims
Verification A store lookup A signature check
Logout and revocation Immediate: delete the session Only at expiry, or with a revocation list
Size Tens of bytes Hundreds of bytes, growing with the claims
CSRF Exposed, since the cookie is sent automatically Not applicable if the token goes in Authorization
XSS An HttpOnly cookie is out of the script's reach A token in localStorage is readable by scripts
Several instances Shared store or sticky sessions All they need is the verification key
Typical use Website and web app login Service-to-service APIs, mobile apps, SSO

Size depends on the content. In the example above, the JWT with only sub, iat and exp is 127 characters long; an RS256 signature with a 2048-bit key alone takes 342. If the token goes in a cookie, RFC 6265 only guarantees 4096 bytes per cookie, counting name, value and attributes.

How do logout and revocation work?#

With a session, signing out means deleting a record. Password changed, phone lost, account suspended? Delete that user's sessions and the next request fails.

With a JWT, the token stays valid until exp, because the server checks nothing to accept it. There are three ways out, and all of them bring some state back to the server:

  1. A short access token. The OWASP Top 10:2025 recommends that stateless JWTs be short-lived, to shrink the window for whoever steals one. Minutes, not days.
  2. A rotating refresh token. A long, opaque token stored on the server that only serves to request a new access token. RFC 9700, the OAuth 2.0 security best practices, describes rotation: each use issues a new refresh token and invalidates the previous one; if an already-used token shows up again, the server revokes the active one, because one of the two parties is an attacker.
  3. A revocation list. Store the jti of revoked tokens until they expire. OWASP notes that the solution then stops being fully stateless, and suggests considering plain server-side sessions: if you are going to query a store on every request anyway, JWT's main advantage shrinks.

This is where the two approaches swap risks.

A cookie goes out on its own with every request to the domain, including requests another site triggers. That is CSRF: a malicious page makes the victim's browser send an authenticated POST. SameSite cuts much of it, but OWASP treats it as defense in depth, not as a replacement for a CSRF token (how the attack and its defenses work). Don't rely on the browser default: according to MDN, only some browsers treat a cookie without SameSite as Lax, so set the value explicitly.

localStorage has no CSRF problem, because the token only goes on a request if your code puts it in the header. In exchange, any script on the page can read the token. OWASP is blunt: do not store JWTs, refresh tokens or session IDs in localStorage or sessionStorage, because a single XSS exposes all of them; use an HttpOnly, Secure, SameSite=Strict cookie instead, or a backend-for-frontend (BFF), where the token never reaches the browser. The same OWASP warns that XSS defeats every CSRF protection, so XSS is the first risk to close, with either approach.

The usual middle ground in SPAs is the one in the example: a short access token in memory (a JavaScript variable, lost on page reload) and the refresh token in that cookie, scoped to the refresh path.

What about several instances behind a load balancer?#

With sessions in process memory and two or more instances behind a load balancer, the next request may land on an instance that has never seen that session, and the user is sent back to the login screen for no visible reason.

There are two ways out. Sticky sessions always send the same client to the same instance, but if that instance goes down its sessions go with it, and the load spreads less evenly. The other is to move the session into a shared store. Redis is the common choice: it answers fast and deletes a key on its own when its TTL runs out, which is a session's lifecycle; connect-redis uses the cookie's expiry as the TTL.

With JWT, any instance verifies the token, as long as all of them have the same key. That is JWT's real advantage here. But refresh tokens and the revocation list, if you have them, also need a shared place, and it is usually the same Redis.

When should you choose each one?#

Choose cookie sessions when the client is a browser talking to your own backend on the same site: a website login, an admin area, an online store. Immediate logout, an HttpOnly cookie and little to get wrong.

Choose JWT when the token has to be verified by services that don't share a store: microservices, an API used by mobile apps, single sign-on across domains (SSO, usually through OpenID Connect).

Combine both when it makes sense: many systems use sessions on the website and JWTs on the public API. There is no universal winner. If the question is what each user may do after signing in, that is a different layer: see authentication vs authorization.

How to do this on Square Cloud#

On Square Cloud, load balancing puts the same custom domain on 2 or more applications, with round-robin and automatic failover, from the Standard plan (up to 2 applications per domain on Standard, 5 on Pro and 10 on Enterprise). There are no sticky sessions, and each application has its own disk: neither in-memory nor file-based sessions survive a switch between instances, so the session goes to Redis.

Redis hosting, also from the Standard plan, sits in the same datacenter as your applications, with about 1 ms of average latency, persistence and mandatory TLS (rediss://, with the CA certificate you download from the dashboard). Copy the connection URL into the REDIS_URL variable of each application, together with SESSION_SECRET or JWT_SECRET: each application has its own variables, and every instance needs the same secret. Redis closes idle clients after 5 minutes, so keep the client's automatic reconnection on (node-redis reconnects by default; if you see Socket closed unexpectedly, read Redis connection errors), and keep in mind the limit of up to 256 connections per database: one client per instance is enough.

See Redis hosting.

Infrastructure

L3/L4/L7 DDoS mitigation and a WAF on every plan

Redis hosting

FAQs

Is JWT more secure than sessions?

Neither is more secure by nature. Security comes from the details: HttpOnly and Secure cookies, a strong secret, a pinned algorithm on verification and a short expiry. A misconfigured JWT is worse than a well-built session, and the reverse is also true.

Can I invalidate a JWT before it expires?

Only by keeping state on the server, such as a list of revoked tokens (by jti) checked on every request. That is why the usual setup issues access tokens that last minutes and controls renewal with a refresh token the server can delete.

Can I store the JWT in localStorage?

You can, but any script running on the page can read it, so an XSS flaw steals the token. OWASP recommends keeping JWTs, refresh tokens and session IDs out of localStorage and in an HttpOnly, Secure, SameSite=Strict cookie, which JavaScript cannot read.

Do I need Redis to use sessions?

With a single instance, not necessarily: the database you already use can be the store. What does not work in production is the process memory, which loses every session on restart. With several instances and no sticky sessions, Redis is the usual choice.

Is the JWT payload encrypted?

No. In a signed JWT the payload is only Base64url-encoded: anyone holding the token can read every claim. The signature prevents changes, not reading, so keep sensitive data out of it.

Next articleWhat is SQL injection and how to prevent itSQL injection happens when user input becomes part of a SQL query. See how the attack works and how to prevent it with parameterized queries in Node.js and Python.

More in Security

See all 24 articles