Authentication with JWT in Node.js

By Published 9 min read

Authentication with JWT in Node.js

Introduction:

In the last lesson we built a REST API with Node.js and Express (see Building a REST API with Node.js and Express). Anyone could call every route of that API. Real apps need to know who is calling and what they are allowed to do.

That is what authentication is about. One of the most popular ways to do it in Node.js is with a JSON Web Token, or JWT (people say “jot”). In this tutorial you will learn what a JWT really is, how it is signed and checked, and then you will build a small but complete login system:

  • Register a user and store the password safely
  • Log in and receive an access token and a refresh token
  • Protect routes with a middleware
  • Allow some routes only for admins
  • Get a new access token with a refresh token, and log out

Every example below was run with Node.js, Express 5 and the jsonwebtoken package, and the outputs in the comments are real.

What Is a JWT?

A JWT is a string made of three parts separated by dots:

xxxxx.yyyyy.zzzzz
header.payload.signature

1. Header:

The header is a small JSON object that says which algorithm signed the token:

{ "alg": "HS256", "typ": "JWT" }

2. Payload:

The payload holds the claims, which is information about the user and the token itself. Some claim names are standard:

  • sub (subject): who the token is about, usually the user ID
  • iat (issued at): when the token was created, in seconds
  • exp (expires): when the token stops being valid
  • jti (JWT ID): a unique ID for this token

You can add your own claims too, like role.

3. Signature:

The server takes the encoded header and payload, and signs them with a secret key. With HS256 this is an HMAC using SHA-256. If anyone changes even one character of the header or payload, the signature no longer matches.

The header and payload are only Base64URL encoded, not encrypted. Anyone who has the token can read them. So never put passwords or private data inside a JWT. The signature does not hide the data, it only proves that the server created it and nobody changed it.

Creating and Reading a Token:

Install the packages first:

npm install express jsonwebtoken

Now create a token and look inside it:

const jwt = require("jsonwebtoken");
const SECRET = "dev-only-secret-change-me-0123456789abcdef";

const token = jwt.sign({ sub: "42", name: "Aisha", role: "admin" }, SECRET, { expiresIn: "15m" });
console.log(token.slice(0, 36) + "...");
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

const [header, payload] = token.split(".");
const decode = (part) => JSON.parse(Buffer.from(part, "base64url").toString());

console.log(decode(header));
// { alg: 'HS256', typ: 'JWT' }

const data = decode(payload);
console.log(data.sub, data.name, data.role, data.exp - data.iat);
// 42 Aisha admin 900

See how we read the payload without the secret? That is the point made above: the data is visible to anyone. The exp - iat value is 900 seconds, which is our 15 minutes.

If you want to look inside a token while debugging, you can paste it into a tool like the Eskillsfy JWT Decoder. Only do that with test tokens, never with a real user’s token from production.

Verifying a Token:

Reading a token is easy. Trusting it needs jwt.verify, which checks the signature and the expiry:

console.log(jwt.verify(token, SECRET).name);
// Aisha

Let’s try to cheat. We change the role in the payload to superadmin and keep the old signature:

const [h, p, s] = token.split(".");
const fake = Buffer.from(JSON.stringify({ ...data, role: "superadmin" })).toString("base64url");

try {
  jwt.verify(`${h}.${fake}.${s}`, SECRET);
} catch (e) {
  console.log(e.name + ": " + e.message);
}
// JsonWebTokenError: invalid signature

The library caught it. The same happens with the wrong secret, and with a token that is too old:

try { jwt.verify(token, "wrong-secret"); } catch (e) { console.log(e.message); }
// invalid signature

const old = jwt.sign({ sub: "42", iat: Math.floor(Date.now() / 1000) - 3600 }, SECRET, { expiresIn: "15m" });
try { jwt.verify(old, SECRET); } catch (e) { console.log(e.name + ": " + e.message); }
// TokenExpiredError: jwt expired

1. What does the signature really do?

It is just an HMAC. You can compute it yourself with the built-in crypto module and get the exact same value:

const crypto = require("node:crypto");
const sig = crypto.createHmac("sha256", SECRET).update(`${h}.${p}`).digest("base64url");
console.log(sig === s);
// true

So the security of HS256 depends completely on the secret. Use a long random value (32 bytes or more), keep it in an environment variable, and never commit it to Git.

2. Always fix the algorithm:

An old attack sends a token with "alg": "none" and no signature. Good libraries reject it, but you should still tell verify which algorithms you accept:

const noneHeader = Buffer.from(JSON.stringify({ alg: "none", typ: "JWT" })).toString("base64url");
const noneToken = `${noneHeader}.${p}.`;

try {
  jwt.verify(noneToken, SECRET, { algorithms: ["HS256"] });
} catch (e) {
  console.log(e.name + ": " + e.message);
}
// JsonWebTokenError: jwt signature is required

Building the Login System:

Now let’s put it together in one Express app. To keep the focus on JWT, users live in a Map in memory. In a real app they would be in a database.

1. Hashing passwords:

Never store a plain password. Node.js has scrypt built in, which is a slow, salted hash made for passwords, so we don’t need an extra package:

const crypto = require("node:crypto");
const { promisify } = require("node:util");
const scrypt = promisify(crypto.scrypt);

async function hashPassword(password) {
  const salt = crypto.randomBytes(16).toString("hex");
  const key = await scrypt(password, salt, 64);
  return `${salt}:${key.toString("hex")}`;
}

async function verifyPassword(password, stored) {
  const [salt, keyHex] = stored.split(":");
  const key = await scrypt(password, salt, 64);
  return crypto.timingSafeEqual(key, Buffer.from(keyHex, "hex"));
}

Each user gets their own random salt, so two people with the same password get different hashes. timingSafeEqual compares the bytes in constant time, so an attacker cannot learn anything from how long the check takes.

2. Issuing two tokens:

We give the user two tokens at login:

  • An access token that lives for 15 minutes. It is sent with every API request.
  • A refresh token that lives for 7 days. It is used only to get a new access token.

Short access tokens limit the damage if one leaks. The refresh token gets a unique jti, and we remember which ones are still valid, so we can cancel them later.

const jwt = require("jsonwebtoken");

const ACCESS_SECRET = process.env.ACCESS_SECRET;
const REFRESH_SECRET = process.env.REFRESH_SECRET;

const users = new Map();          // email -> { id, email, passwordHash, role }
const refreshTokens = new Set();  // jti of refresh tokens that are still valid

function issueTokens(user) {
  const accessToken = jwt.sign({ sub: user.id, role: user.role }, ACCESS_SECRET, {
    algorithm: "HS256",
    expiresIn: "15m",
  });
  const jti = crypto.randomUUID();
  const refreshToken = jwt.sign({ sub: user.id }, REFRESH_SECRET, {
    algorithm: "HS256",
    expiresIn: "7d",
    jwtid: jti,
  });
  refreshTokens.add(jti);
  return { accessToken, refreshToken };
}

Notice we use different secrets for the two kinds of token. That way a refresh token can never be used as an access token, and the other way around.

3. The auth middleware:

The client sends the access token in a header: Authorization: Bearer <token>. A middleware reads it, verifies it and saves the payload on req.user:

function requireAuth(req, res, next) {
  const header = req.headers.authorization || "";
  const [scheme, token] = header.split(" ");
  if (scheme !== "Bearer" || !token) {
    return res.status(401).json({ error: "Missing bearer token" });
  }
  try {
    req.user = jwt.verify(token, ACCESS_SECRET, { algorithms: ["HS256"] });
    next();
  } catch (err) {
    const message = err.name === "TokenExpiredError" ? "Token expired" : "Invalid token";
    res.status(401).json({ error: message });
  }
}

function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) return res.status(403).json({ error: "Forbidden" });
    next();
  };
}

Remember the difference between the two status codes: 401 means “I don’t know who you are”, and 403 means “I know who you are, but you are not allowed”.

4. Register and login routes:

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

app.post("/auth/register", async (req, res) => {
  const { email, password } = req.body ?? {};
  if (!email || !password || password.length < 8) {
    return res.status(400).json({ error: "Email and a password of 8+ characters are required" });
  }
  if (users.has(email)) return res.status(409).json({ error: "Email already registered" });
  const user = { id: String(users.size + 1), email, role: "user", passwordHash: await hashPassword(password) };
  users.set(email, user);
  res.status(201).json({ id: user.id, email: user.email });
});

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

The login error is the same for a wrong email and a wrong password. If they were different, an attacker could find out which emails have accounts.

5. Protected routes:

Now we just put the middleware in front of the routes that need it:

app.get("/me", requireAuth, (req, res) => {
  const user = [...users.values()].find((u) => u.id === req.user.sub);
  res.json({ id: user.id, email: user.email, role: user.role });
});

app.get("/admin/stats", requireAuth, requireRole("admin"), (req, res) => {
  res.json({ users: users.size });
});

6. Refresh and logout:

When the access token expires, the client calls /auth/refresh with its refresh token. We check it, delete the old one and issue a fresh pair. This is called refresh token rotation: each refresh token works only once, so a stolen one that was already used is useless.

app.post("/auth/refresh", (req, res) => {
  const { refreshToken } = req.body ?? {};
  try {
    const payload = jwt.verify(refreshToken, REFRESH_SECRET, { algorithms: ["HS256"] });
    if (!refreshTokens.has(payload.jti)) throw new Error("revoked");
    refreshTokens.delete(payload.jti);
    const user = [...users.values()].find((u) => u.id === payload.sub);
    if (!user) throw new Error("no user");
    res.json(issueTokens(user));
  } catch {
    res.status(401).json({ error: "Invalid refresh token" });
  }
});

app.post("/auth/logout", (req, res) => {
  const payload = jwt.decode(req.body?.refreshToken ?? "");
  if (payload?.jti) refreshTokens.delete(payload.jti);
  res.status(204).end();
});

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

A new refresh also picks up changes to the user. If you make someone an admin, their next access token will carry the new role.

Testing the Whole Flow:

Here is what happened when we called the API step by step with fetch (status code, then the response body):

POST /auth/register  (new email)         -> 201 { id: '1', email: 'aisha@example.com' }
POST /auth/register  (same email)        -> 409 { error: 'Email already registered' }
POST /auth/login     (wrong password)    -> 401 { error: 'Invalid email or password' }
POST /auth/login     (right password)    -> 200 { accessToken, refreshToken }
GET  /me             (no token)          -> 401 { error: 'Missing bearer token' }
GET  /me             (access token)      -> 200 { id: '1', email: 'aisha@example.com', role: 'user' }
GET  /me             (token edited)      -> 401 { error: 'Invalid token' }
GET  /admin/stats    (role user)         -> 403 { error: 'Forbidden' }
GET  /me             (expired token)     -> 401 { error: 'Token expired' }
POST /auth/refresh   (refresh token)     -> 200 new pair
POST /auth/refresh   (same token again)  -> 401 { error: 'Invalid refresh token' }
GET  /admin/stats    (after promotion)   -> 200 { users: 1 }
POST /auth/logout                        -> 204
POST /auth/refresh   (after logout)      -> 401 { error: 'Invalid refresh token' }

You can try the same with curl:

curl -X POST localhost:3000/auth/login -H "Content-Type: application/json" \
  -d '{"email":"aisha@example.com","password":"correct horse"}'

curl localhost:3000/me -H "Authorization: Bearer <accessToken>"

Where Should the Client Keep the Token?

This question comes up in every project. Here are the common choices:

  • Memory (a JavaScript variable): the safest place for the access token. It is lost on page reload, which is fine because you can get a new one with the refresh token.
  • httpOnly cookie: a good place for the refresh token. JavaScript cannot read it, so an XSS bug cannot steal it. Add Secure and SameSite=Strict or Lax, and protect the refresh route against CSRF.
  • localStorage: easy, but any script on your page can read it. If you have an XSS bug, the token is gone.

For mobile apps, use the secure storage of the platform (Keychain on iOS, Keystore on Android).

Common Mistakes to Avoid:

1. Putting secrets in the payload:

The payload is readable by anyone. Store only IDs and roles.

2. Tokens that never expire:

A token without exp works forever if it leaks. Keep access tokens short.

3. A weak or hard-coded secret:

"secret" or "123456" can be guessed by brute force. Generate one with node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" and load it from an environment variable.

4. Using jwt.decode to check a user:

decode does not check the signature. Use it only for things like logout, where trusting the data is not needed. Use verify everywhere else.

5. Thinking you can cancel an access token:

A JWT is valid until it expires, because the server does not store it. That is why we keep access tokens short and keep a list only for refresh tokens. If you need instant logout everywhere, you need a server-side check (for example a “token version” on the user, or a deny list in Redis).

6. Sending tokens over plain HTTP:

Anyone on the network could copy the token. Always use HTTPS in production.

JWT or Sessions?

JWTs are not always the best choice. A classic session stores the user’s data on the server and gives the browser only a random session ID in a cookie.

  • Use sessions for a normal website where the server and the pages live together. They are simple, and logout is instant.
  • Use JWTs when many services or mobile apps need to check the user without asking one central server, or for API-to-API calls.

Many real apps mix both: a refresh token in an httpOnly cookie, and short-lived JWT access tokens for the API.

Conclusion:

A JWT is a signed, readable package of claims. The signature proves the server made it, and the expiry limits how long it works. With Node.js and Express you can build a solid login flow in about 100 lines: hash passwords with scrypt, issue a short access token and a longer refresh token, check them in a middleware, use roles for authorization, and rotate refresh tokens so they can be used only once.

Keep the secret long and private, fix the algorithm in verify, never put private data in the payload, and always use HTTPS.

In the next lesson, we will make our API faster with Caching in Node.js with Redis.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume