Skip to main content
CodingMarble

Programming fundamentals

Authentication: Sessions vs JWT Explained Clearly

A session keeps the login state on the server and gives the browser an opaque ID in a cookie, while a JSON Web Token carries signed claims inside the token itself. Sessions are easier to revoke and are the safer default for a single web app; JWTs suit cases where several services must verify a user without sharing a session store.

By CodingMarble · Published · 5 min read

A laptop turned on showing code
Photo: Andras Vas on Unsplash

Authentication and authorisation are different questions

Authentication answers who you are. Authorisation answers what you are allowed to do. A login form is authentication: you prove an identity with a password, a one-time code or a passkey. Checking whether that identity may delete an invoice is authorisation, and it has to run on every request that touches protected data, not just once at login.

HTTP is stateless, so the server forgets you between requests. Sessions and tokens are two ways of solving the same problem: after a successful login, give the client something it can present on every later request so the server can recognise it. The debate about sessions versus JWTs is really a debate about where the memory of that login lives, on the server or inside the token.

Server-side sessions with cookies

With a session, the server creates a record after login, for example a row in a database or an entry in a fast key-value store, holding the user ID and an expiry time. It sends the browser a random, unguessable session ID in a cookie. The browser returns that cookie automatically on each request, and the server looks the ID up to find out who is calling.

The cookie holds no user data, only a pointer. That is the main strength of the design: the server is the single source of truth. To log someone out everywhere, delete their session records. To ban an account, delete its sessions and the next request fails. The cost is a lookup on every request and, once you run several servers, a shared store they can all reach.

Prompt· A session cookie as the server sends it, with the flags that matter
Set-Cookie: sid=9f3c1a7e5b2d4c88a0e1f6b7d2c3a4e5; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400

JSON Web Tokens in plain terms

A JSON Web Token is a string with three dot-separated parts: a header naming the signing algorithm, a payload of claims such as the user ID and an expiry time, and a signature. The payload is only encoded, not encrypted, so anyone holding the token can read it. What the signature adds is tamper evidence: a server that knows the signing key can check the token was issued by it and has not been altered.

Because the token describes itself, the server can verify it without a database lookup. That is attractive when many separate services need to trust a login, since each can verify the signature on its own. The price is that the server holds no record to delete. A signed token stays valid until it expires, even if the user logs out or is banned, unless you add a deny-list, which reintroduces the server-side state you were avoiding.

JavaScript· Reading a JWT payload shows why you must never put secrets in it
const token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiIsImV4cCI6MTc2NDAwMDAwMH0.signature";
const payload = token.split(".")[1];
const json = Buffer.from(payload, "base64url").toString("utf8");
console.log(JSON.parse(json)); // { sub: '42', exp: 1764000000 }

Storage, XSS and CSRF: the real trade-offs

Where the credential lives in the browser decides which attacks matter. A cookie marked HttpOnly cannot be read by JavaScript, so a cross-site scripting (XSS) bug cannot simply copy it out. A token kept in localStorage or in a JavaScript variable can be read by any script running on your page, including an injected one. That is the usual argument against storing long-lived tokens in localStorage.

Cookies bring the opposite risk, cross-site request forgery (CSRF): the browser attaches cookies to requests even when another site triggers them. SameSite=Lax or Strict blocks most of this, and for state-changing requests you can add a CSRF token or check the Origin header. Secure keeps the cookie off plain HTTP. Note that a JWT can also travel in a cookie, and then you get the same CSRF concerns; the format and the transport are separate choices.

  • HttpOnly: JavaScript cannot read the cookie, which limits damage from XSS.
  • Secure: the cookie is only sent over HTTPS.
  • SameSite: Lax or Strict stops the browser sending the cookie on most cross-site requests, which reduces CSRF.
  • Max-Age or Expires: keep sessions short, and rotate the ID after login to prevent session fixation.

Refresh tokens at overview level

Because a JWT cannot be recalled, teams make access tokens short-lived and pair them with a refresh token. The access token, valid for minutes, goes with each API call. The refresh token, valid for days, is sent only to one endpoint to obtain a new access token. Since the refresh token is stored on the server side as a record, you can revoke it, which regains some control.

A common hardening step is rotation: each use of a refresh token issues a new one and invalidates the old, so a stolen token that is reused can be detected. This pattern works, but notice what it has become: a server-side session with extra steps. That is not a criticism, only a reason to ask whether you needed the extra moving parts in the first place.

Which one fits your project

For a typical website or dashboard where one backend serves one frontend, server-side sessions in an HttpOnly, Secure, SameSite cookie are the simpler and safer default. Logout works, bans work, and there is nothing sensitive in the browser beyond an opaque ID. Mature frameworks ship session handling already, so use theirs rather than assembling your own.

JWTs earn their place when a mobile app and several independent services must verify the same identity, when you delegate login to an identity provider that issues signed tokens, or when you need short-lived, narrowly scoped credentials between services. Whichever you pick, verify the algorithm and expiry on every check, reject tokens that claim no signature, and keep the signing key out of source control.

Practical tip: open your browser's developer tools, go to the Application or Storage tab, and look at your own login. Can JavaScript see the credential, or is it an HttpOnly cookie? Try logging out and replaying the old request from the Network tab. If it still succeeds, your logout does not really revoke anything.

What you should never write yourself

Never store passwords in plain text, and never protect them with a fast general-purpose hash such as plain SHA-256 or MD5. Fast hashes let an attacker who steals your database test billions of guesses per second. Use a slow, salted password-hashing algorithm designed for the job: Argon2, scrypt or bcrypt. The salt is a random value stored with each hash so identical passwords produce different results, and the slowness is deliberate.

JavaScript· Salted scrypt with Node's built-in crypto, compared in constant time
import { scryptSync, randomBytes, timingSafeEqual } from "node:crypto";

export function hashPassword(password) {
  const salt = randomBytes(16);
  const hash = scryptSync(password, salt, 64);
  return salt.toString("hex") + ":" + hash.toString("hex");
}

export function verifyPassword(password, stored) {
  const [saltHex, hashHex] = stored.split(":");
  const expected = Buffer.from(hashHex, "hex");
  const actual = scryptSync(password, Buffer.from(saltHex, "hex"), 64);
  return timingSafeEqual(expected, actual);
}

Prefer a maintained library or your framework's built-in hasher over copying this, and check its documentation for the current recommended cost settings, because sensible values change as hardware improves. The same advice covers token signing, session ID generation and password reset flows: use well-reviewed libraries, and spend your effort on configuration and testing instead of invention.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.