# Signed, Not Encrypted: How JWT Authentication Works in Express.js

Take any JWT your server issues, split it on `.`, and decode the middle part in Node.js — without knowing the secret key:

```js
// No secret key needed to read a JWT's header or payload
// (token is the string returned by POST /login, shown below)
const [headerB64, payloadB64] = token.split(".");
console.log("header: ", Buffer.from(headerB64, "base64url").toString("utf8"));
console.log("payload:", Buffer.from(payloadB64, "base64url").toString("utf8"));
```

```text
header:  {"alg":"HS256","typ":"JWT"}
payload: {"sub":1,"email":"asha@example.com","role":"member","iat":1795522448,"exp":1795523348}
```

Anyone holding a JWT can read its payload. A JWT is **signed, not encrypted**. Its job is not to hide data — its job is to prove the server issued the token and nobody altered it since.

Every output below comes from a real run on **Node.js 24.22.1**, **Express 5.3.0**, and **jsonwebtoken 9.0.3**.

## Why authentication is needed (and what stateless auth means)

HTTP is **stateless**: each request arrives without memory of the previous one. When a user logs in on `POST /login` and then opens `GET /profile`, the server has no built-in way to know both requests came from the same person.

**Authentication** verifies who the caller is (usually by checking credentials once at login and issuing a proof for later requests). There are two common ways to carry that proof:
- **Session-based (stateful):** the server stores a session record in a database or Redis and hands the client a random session ID. Every later request looks up that ID on the server.
- **Token-based (stateless, such as JWT):** the server packs the user's ID and role into a signed token and hands it to the client. On later requests, the server verifies the signature mathematically without needing a session table lookup.

Think of a stamped concert wristband: security does not check a guest list on every re-entry — they check that the stamp is genuine and still valid.

## Structure of a JWT: header, payload, signature

A **JWT (JSON Web Token)** is a string made of three Base64URL-encoded pieces joined by dots:

```text
<header>.<payload>.<signature>
```

1. **Header:** metadata about the token — the signing algorithm (`"alg": "HS256"`) and token type (`"typ": "JWT"`).
2. **Payload:** the claims (data) you attach, such as `"sub": 1` (subject / user ID), `"role": "member"`, `"iat"` (issued-at timestamp), and `"exp"` (expiry timestamp). Because it is Base64URL-encoded, never store passwords, API keys, or sensitive personal data here.
3. **Signature:** generated by hashing the encoded header and payload together with a secret key that only your server knows. If someone changes `"role": "member"` to `"role": "admin"` in the payload, the signature no longer matches and verification fails.

| Part | Encoded as | Readable by client? | Protected against tampering? |
|---|---|---|---|
| Header | Base64URL JSON | Yes | Yes (covered by signature) |
| Payload | Base64URL JSON | Yes | Yes (covered by signature) |
| Signature | Hash using server secret | Opaque bytes | Proves integrity of header + payload |

## Login flow using JWT

Install Express and `jsonwebtoken` (`npm install express jsonwebtoken`). When a user logs in with valid credentials, the server signs a short-lived token and returns it:

```js
// server.js (Node.js 24.22.1, Express 5.3.0, jsonwebtoken 9.0.3)
const express = require("express");
const jwt = require("jsonwebtoken");

const app = express();
app.use(express.json());

// Run locally with: JWT_SECRET="dev-secret-change-me" node server.js
const SECRET = process.env.JWT_SECRET;
if (!SECRET) throw new Error("JWT_SECRET environment variable is required");

app.post("/login", (req, res) => {
  const { email, password } = req.body || {};
  // Local demo only: real apps verify a hashed password from a database
  if (email !== "asha@example.com" || password !== "pass123") {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  const token = jwt.sign({ sub: 1, email, role: "member" }, SECRET, {
    algorithm: "HS256",
    expiresIn: "15m",
  });
  res.status(200).json({ token });
});
```

<!-- mermaid source: arrows are written as --&gt; so this comment stays hidden; replace &gt; with > before reusing
flowchart LR
    C["Client"] --&gt;|"1. POST /login<br/>email + password"| S["Express Server<br/>verify credentials"]
    S --&gt;|"2. Sign JWT<br/>secret + exp 15m"| T["JWT<br/>header.payload.sig"]
    T --&gt;|"3. Return token"| C
-->
![JWT login authentication flow: the client sends email and password to POST /login; Express verifies credentials, signs a JWT with the server secret and 15m expiry, and returns the token; the client stores the token and sends Authorization: Bearer token on later requests](https://mermaid.ink/img/pako:eNo9zTtvwkAQBOC_stqWcIhEaayIxqKJkIiwpRReiotvbZ9yD2vveAn47xGEpJ6Zb87YRsNYYOfioR20ZFhtKAAAlA1h6SyHTLiF6XRxIZwr-FhXNcxc7G14-5LZgr22DiYw6pQOUQzhBaqGcHkchVOCimXPcq_uWWx3glbYcMhWu0S4_T2rHgfPCirbB3j_rO-TxK1whgnwcYT5q7_pdUP4lw-sDYsa9clFbVSy_T9ZP8gXBRvOOwmQ4zeHm1DiE3oWr63BAs-EeWDPhAWh4U7vXCa84vUHMHNbqQ==?type=png)

Notice `expiresIn: "15m"`. `jsonwebtoken` turns that into the `"exp"` claim inside the payload automatically, so the token stops working 15 minutes after login. Also notice the generic `"Invalid credentials"` error on failure — returning the same message for an unknown email and a wrong password avoids revealing which emails exist in your system.

## Sending tokens and protecting routes

On subsequent requests, the client sends the token in the `Authorization` HTTP header with the `Bearer` prefix:

```text
Authorization: Bearer <header>.<payload>.<signature>
```

From JavaScript (browser or Node.js `fetch`), that looks like:

```js
const res = await fetch("http://127.0.0.1:3000/profile", {
  headers: { Authorization: `Bearer ${token}` },
});
```

On the server, a middleware extracts the token, verifies its signature and expiry with `jwt.verify`, attaches the decoded claims to `req.user`, and calls `next()`. Notice that the middleware does **not** return `403 Forbidden` when a token is missing or invalid — `401 Unauthorized` means "we do not know who you are", while `403` means "we know who you are, and you lack permission for this route":

```js
function requireJwt(req, res, next) {
  const header = req.headers.authorization || "";
  if (!header.startsWith("Bearer ")) {
    return res.status(401).json({ error: "Missing Bearer token" });
  }
  const token = header.slice(7);
  try {
    req.user = jwt.verify(token, SECRET, { algorithms: ["HS256"] });
    next();
  } catch (err) {
    // Returning err.message here makes the failure reason visible; in production, return a generic message
    return res.status(401).json({ error: err.message });
  }
}

app.get("/profile", requireJwt, (req, res) => {
  res.status(200).json({ id: req.user.sub, email: req.user.email, role: req.user.role });
});

app.listen(3000, () => console.log("Listening on http://127.0.0.1:3000"));
```

<!-- mermaid source: arrows are written as --&gt; so this comment stays hidden; replace &gt; with > before reusing
flowchart LR
    Req["GET /profile<br/>Bearer token"] --&gt; MW{"requireJwt<br/>jwt.verify()"}
    MW -- "missing / tampered<br/>/ expired" --&gt; E["401 Unauthorized"]
    MW -- "valid" --&gt; Attach["Attach req.user<br/>call next()"]
    Attach --&gt; Route["/profile Handler<br/>200 OK"]
-->
![Token validation lifecycle on a protected route: client sends GET /profile with Authorization Bearer header; requireJwt middleware runs jwt.verify with secret and HS256; if missing, tampered, or expired it returns 401; if valid it attaches req.user and calls next() to reach the /profile handler returning 200](https://mermaid.ink/img/pako:eNpVj1FLhFAQhf_KME8FuVr0JLFQsBTVEkixD44PNx3z1vWq43XdEv976LoP-3ZgzvcxZ8C0yhhDzE3Vp4USB68RWQCAiJuY8HHzDn4tVa4N332Kv35gJSzgqh-2hAl43hq2u4FQuOm08HPv5t5371Z7Fp3_XlwSjkfndgeeB4Slblttv8AHp8qahbOZ8YEPtRbOCGfvJia8Da7hw6rOFZXov-mUnLv2yugTcO-cSouY8BhAuFl1LctsT5UxYPngpocWydKb2KjqHMeEp7XwpGxmFvYmCODthTDBKyxZSqUzDHEgdAWXTBgSZpyrzjjCEcd_5y5tlw==?type=png)

## Real HTTP runs: valid, tampered, and expired tokens

I ran this server on Node.js 24.22.1 with Express 5.3.0 and `jsonwebtoken` 9.0.3 and tested five cases: logging in, calling `/profile` with no header, calling with the valid token, modifying `"role"` to `"admin"` in the payload, and sending an expired token. Start the server with `JWT_SECRET="dev-secret-change-me" node server.js`, then run this client in a second terminal with the same `JWT_SECRET` set:

```js
// client.js (run while server.js is listening; JWT_SECRET must match the server's)
const jwt = require("jsonwebtoken");

const base = "http://127.0.0.1:3000";

async function get(label, token) {
  const res = await fetch(base + "/profile", {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  });
  console.log(`GET /profile (${label}) -> ${res.status} ${await res.text()}`);
}

(async () => {
  const login = await fetch(base + "/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email: "asha@example.com", password: "pass123" }),
  });
  const { token } = await login.json();
  console.log(`POST /login -> ${login.status} token parts: ${token.split(".").length}`);

  await get("no header");
  await get("valid", token);

  // Tampered: change the role in the payload, keep the original signature
  const [header, payload, signature] = token.split(".");
  const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
  const forged = Buffer.from(JSON.stringify({ ...claims, role: "admin" })).toString("base64url");
  await get("tampered", `${header}.${forged}.${signature}`);

  // Expired: a token whose expiry is already in the past
  const { iat, exp, ...rest } = claims; // sign() sets these itself
  const expired = jwt.sign(rest, process.env.JWT_SECRET, { expiresIn: -10 });
  await get("expired", expired);
})();
```

Real output:

```text
POST /login -> 200 token parts: 3
GET /profile (no header) -> 401 {"error":"Missing Bearer token"}
GET /profile (valid) -> 200 {"id":1,"email":"asha@example.com","role":"member"}
GET /profile (tampered) -> 401 {"error":"invalid signature"}
GET /profile (expired) -> 401 {"error":"jwt expired"}
```

When I rewrote the payload's role to `"admin"` and kept the original signature, `jwt.verify` rejected it immediately with `invalid signature`. When the expiry passed, it rejected with `jwt expired`.

## Security essentials for JWT authentication

Authentication sits directly on a trust boundary. Five concrete rules prevent the most common JWT vulnerabilities:
1. **Never put sensitive data in the payload.** Base64URL is readable by anyone who sees the token. Keep claims minimal (`sub`, `role`).
2. **Store `JWT_SECRET` in environment variables** (at least 256 bits of random bytes for `HS256`) and fail fast at startup if it is missing — never commit it to Git or use an `|| "fallback"` default.
3. **Pin `algorithms: ["HS256"]` in `jwt.verify`.** Explicitly stating the expected algorithm protects against algorithm-confusion attacks where a forged token specifies `"alg": "none"` or another algorithm.
4. **Keep access tokens short-lived (`expiresIn: "15m"`).** A stolen token with no expiry stays valid forever.
5. **Think carefully about browser storage.** Saving a JWT in `localStorage` makes it readable by any JavaScript on the page (vulnerable to XSS). Storing it in an `HttpOnly`, `Secure`, `SameSite` cookie hides it from JavaScript, though you then need CSRF awareness on state-changing routes.

## When NOT to use stateless JWTs

Stateless JWTs have one major trade-off: **you cannot revoke a valid token before it expires** without adding server-side state.

If a user clicks "Log out of all devices", changes their password, or gets banned, an already-issued JWT still passes `jwt.verify` until its `exp` timestamp runs out. If your app needs instant server-side revocation — and runs on a single backend or already uses Redis — standard server-side sessions are often simpler and safer than rebuilding a token blocklist on top of JWTs.

## Where this leaves you

A JWT is a signed, three-part token (`header.payload.signature`) that lets Express verify identity on every request without a session lookup. Sign with a strong env secret and short expiry on `/login`, pass the token as `Authorization: Bearer <token>`, and verify with pinned `algorithms` in middleware.

One honest limit: this demo skips password hashing (`scrypt`/`bcrypt`/`argon2`), database user lookups, and refresh-token rotation for keeping users signed in past 15 minutes. For your own Node.js apps, do you prefer stateless JWTs or server-side sessions with cookies?

