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

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.
Set-Cookie: sid=9f3c1a7e5b2d4c88a0e1f6b7d2c3a4e5; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400JSON 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.
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.
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.
Keep reading
- Web developmentWebsite Security Basics for Small BusinessesMost small business sites are compromised through outdated plugins, weak or reused passwords and missing basic server settings, not through clever attacks. Cover HTTPS, updates, authentication, security headers, form handling and tested backups, and you remove the common routes in.
- Error fixesFix CORS Error: No Access-Control-Allow-Origin HeaderThe browser blocked a cross-origin request because the server's response did not include permission for your page's origin, in the form of an Access-Control-Allow-Origin header. The fix always lives on the server (or in a proxy you control), not in the front-end fetch call.
- Technology explainedHow Does HTTPS Work? The Padlock, Certificates and HandshakeHTTPS wraps your connection to a website in encryption and checks that the site really controls the domain you typed, so others on the network cannot read or alter the traffic. It does not tell you whether the site itself is honest, because a malicious site can also have a padlock.
- Everyday digital lifeTwo-Factor Authentication Explained: Setup and SafetyTwo-factor authentication asks for a second, different kind of proof after your password, so a stolen password alone cannot open your account. Turn it on first for your email, banking and main social accounts, save the backup codes somewhere safe, and prefer an authenticator app or security key over text messages where you can.
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.