AboutProjectsWorkBlogContact
Home / Blog / Backend, Node.js, NestJS & APIs

Implementing Secure JWT Authentication in Node.js

Access and refresh tokens done properly: rotation, reuse detection, cookies and password hashing in Express.

By Hamza JanzaibNovember 28, 202616 min readIntermediate
Paste it into ChatGPT, Claude or any AI assistant.
  • jwt
  • authentication
  • node.js
  • express
  • security
On this page ยท 16 sections
  • The design in one picture
  • Common mistakes to avoid
  • Setup
  • Step 1: Hash passwords
  • Step 2: Create and verify access tokens
  • Step 3: Store refresh tokens with rotation
  • Step 4: The auth service
  • Step 5: Cookies and routes
  • Step 6: Authenticate requests and check roles
  • Step 7: Client behavior
  • Security checklist
  • Performance considerations
  • Testing the flow
  • Troubleshooting
  • Best practices
  • Conclusion

JSON Web Tokens are easy to generate and surprisingly easy to get wrong. Most JWT vulnerabilities in the wild are not cryptographic breaks; they are design mistakes: tokens that live too long, secrets that are too short, algorithms that are not pinned, tokens stored where JavaScript can steal them, and no way to revoke anything. This guide builds a secure authentication flow in Express with TypeScript: short-lived access tokens, rotating refresh tokens, httpOnly cookies, hashed passwords, validation, role checks and tests.

All code is an example you can adapt. Names like User and db stand for your own data layer.

The design in one picture

Login

  1. 1POST /auth/login

    email + password

  2. 2Verify password

    Argon2id hash check

  3. 3Issue access token

    JWT, 15 min, returned in the body

  4. 4Issue refresh token

    random, 7 days, httpOnly cookie

API request

  1. 1Send access token

    Bearer token in the Authorization header

  2. 2Verify JWT

    signature, expiry, issuer, audience

  3. 3Run the handler

    req.user is available

Refresh

  1. 1POST /auth/refresh

    refresh cookie is sent

  2. 2Look up the token hash

    reuse detected? revoke the family

  3. 3Rotate

    store a new refresh token

  4. 4Return a new access token

    the client retries its request

Short-lived access tokens, rotating refresh tokens

Two kinds of tokens do two different jobs. The access token is short-lived and stateless, so APIs can verify it without a database call. The refresh token is long-lived, opaque and stored server-side (hashed), which is what makes revocation possible.

Common mistakes to avoid

  • Storing tokens in localStorage, where any XSS bug can read them.
  • Long-lived access tokens (days or weeks) with no revocation.
  • Not pinning the verification algorithm, which historically enabled alg: none and algorithm-confusion attacks.
  • Weak or hardcoded secrets.
  • Putting sensitive data in the payload. A JWT is signed, not encrypted; anyone can read it.
  • Reusing refresh tokens forever instead of rotating them.
  • Fast hashing for passwords.

Setup

bash
npm install express jsonwebtoken argon2 cookie-parser zodnpm install -D typescript @types/express @types/jsonwebtoken @types/cookie-parser jest ts-jest supertest @types/jest @types/supertest

Environment variables:

ini
NODE_ENV=productionJWT_ACCESS_SECRET=<at least 32 random bytes, e.g. from: openssl rand -base64 48>JWT_ISSUER=https://api.example.comJWT_AUDIENCE=example-webACCESS_TOKEN_TTL=15mREFRESH_TOKEN_TTL_DAYS=7

Validate configuration at boot so the app never starts with a missing or weak secret:

ts
// src/config.tsimport { z } from "zod";const schema = z.object({  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),  JWT_ACCESS_SECRET: z.string().min(32, "JWT_ACCESS_SECRET must be at least 32 characters"),  JWT_ISSUER: z.string().min(1),  JWT_AUDIENCE: z.string().min(1),  ACCESS_TOKEN_TTL: z.string().default("15m"),  REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(7),});export const config = schema.parse(process.env);

Step 1: Hash passwords

Never store or compare plain-text passwords. Argon2id is the current default recommendation:

ts
// src/auth/password.tsimport argon2 from "argon2";export const hashPassword = (plain: string) =>  argon2.hash(plain, { type: argon2.argon2id });export const verifyPassword = (hash: string, plain: string) =>  argon2.verify(hash, plain);

Step 2: Create and verify access tokens

Pin the algorithm on both sides, and set issuer and audience so a token from another system cannot be replayed against yours:

ts
// src/auth/tokens.tsimport jwt, { type JwtPayload } from "jsonwebtoken";import { createHash, randomBytes } from "node:crypto";import { config } from "../config";export interface AccessClaims extends JwtPayload {  sub: string;  role: "user" | "admin";}export function signAccessToken(userId: string, role: AccessClaims["role"]) {  return jwt.sign({ role }, config.JWT_ACCESS_SECRET, {    algorithm: "HS256",    subject: userId,    issuer: config.JWT_ISSUER,    audience: config.JWT_AUDIENCE,    expiresIn: config.ACCESS_TOKEN_TTL as jwt.SignOptions["expiresIn"],  });}export function verifyAccessToken(token: string): AccessClaims {  return jwt.verify(token, config.JWT_ACCESS_SECRET, {    algorithms: ["HS256"], // never accept whatever the token header says    issuer: config.JWT_ISSUER,    audience: config.JWT_AUDIENCE,  }) as AccessClaims;}// Refresh tokens are random opaque strings, not JWTs.export const generateRefreshToken = () => randomBytes(48).toString("base64url");// Store only a hash, so a database leak does not leak usable tokens.export const hashToken = (token: string) =>  createHash("sha256").update(token).digest("hex");

Refresh tokens do not need to be JWTs. A random value with a server-side record is simpler, easier to revoke and carries no readable payload.

Step 3: Store refresh tokens with rotation

Track a family so reuse of an old token can be detected. The table below is the shape that matters; adapt it to Prisma, SQL or Mongo:

ts
// src/auth/refresh-store.ts (interface; implement with your database)export interface RefreshRecord {  id: string;  userId: string;  familyId: string;     // all tokens descended from one login  tokenHash: string;  expiresAt: Date;  revokedAt: Date | null;  replacedById: string | null;}export interface RefreshStore {  create(r: Omit<RefreshRecord, "id" | "revokedAt" | "replacedById">): Promise<RefreshRecord>;  findByHash(hash: string): Promise<RefreshRecord | null>;  markRotated(id: string, replacedById: string): Promise<void>;  revokeFamily(familyId: string): Promise<void>;}

Step 4: The auth service

ts
// src/auth/auth.service.tsimport { randomUUID } from "node:crypto";import { config } from "../config";import { verifyPassword } from "./password";import { generateRefreshToken, hashToken, signAccessToken } from "./tokens";import type { RefreshStore } from "./refresh-store";type Role = "user" | "admin";export interface UserRepo {  findByEmail(email: string): Promise<{ id: string; role: Role; passwordHash: string } | null>;  findById(id: string): Promise<{ id: string; role: Role } | null>;}export class AuthError extends Error {  constructor(message: string, public status = 401) {    super(message);  }}const refreshExpiry = () =>  new Date(Date.now() + config.REFRESH_TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000);export class AuthService {  constructor(private users: UserRepo, private refreshTokens: RefreshStore) {}  async login(email: string, password: string) {    const user = await this.users.findByEmail(email.toLowerCase());    // Same error for unknown user and wrong password: do not reveal which one failed.    if (!user || !(await verifyPassword(user.passwordHash, password))) {      throw new AuthError("Invalid email or password");    }    const { accessToken, refreshToken } = await this.issue(user.id, user.role, randomUUID());    return { accessToken, refreshToken };  }  async refresh(presented: string) {    const record = await this.refreshTokens.findByHash(hashToken(presented));    if (!record) throw new AuthError("Invalid refresh token");    // A rotated or revoked token being used again means it was probably stolen.    if (record.revokedAt || record.replacedById) {      await this.refreshTokens.revokeFamily(record.familyId);      throw new AuthError("Refresh token reuse detected");    }    if (record.expiresAt < new Date()) throw new AuthError("Refresh token expired");    const user = await this.users.findById(record.userId);    if (!user) throw new AuthError("Invalid refresh token");    // Same family id: this is what lets us revoke the whole chain on reuse.    const next = await this.issue(user.id, user.role, record.familyId);    await this.refreshTokens.markRotated(record.id, next.recordId);    return { accessToken: next.accessToken, refreshToken: next.refreshToken };  }  async logout(presented: string | undefined) {    if (!presented) return;    const record = await this.refreshTokens.findByHash(hashToken(presented));    if (record) await this.refreshTokens.revokeFamily(record.familyId);  }  private async issue(userId: string, role: Role, familyId: string) {    const refreshToken = generateRefreshToken();    const record = await this.refreshTokens.create({      userId,      familyId,      tokenHash: hashToken(refreshToken),      expiresAt: refreshExpiry(),    });    return { accessToken: signAccessToken(userId, role), refreshToken, recordId: record.id };  }}

Run the lookup, issue and markRotated calls inside a database transaction (and lock the row) so two concurrent refresh requests carrying the same token cannot both succeed. Revoking the family on logout means a stolen refresh token stops working as soon as the user signs out.

Step 5: Cookies and routes

Send the refresh token only in a cookie JavaScript cannot read, scoped to the refresh endpoint:

ts
// src/auth/auth.routes.tsimport { Router } from "express";import { z } from "zod";import { config } from "../config";const cookieOptions = {  httpOnly: true,  secure: config.NODE_ENV === "production",  sameSite: "strict" as const,  path: "/auth/refresh",  maxAge: config.REFRESH_TOKEN_TTL_DAYS * 24 * 60 * 60 * 1000,};const loginSchema = z.object({  email: z.string().email(),  password: z.string().min(8).max(200),});export function authRoutes(auth: import("./auth.service").AuthService) {  const router = Router();  router.post("/login", async (req, res, next) => {    try {      const { email, password } = loginSchema.parse(req.body);      const { accessToken, refreshToken } = await auth.login(email, password);      res.cookie("refresh_token", refreshToken, cookieOptions);      res.json({ accessToken });    } catch (err) {      next(err);    }  });  router.post("/refresh", async (req, res, next) => {    try {      const presented = req.cookies?.refresh_token as string | undefined;      if (!presented) return res.status(401).json({ error: "Missing refresh token" });      const { accessToken, refreshToken } = await auth.refresh(presented);      res.cookie("refresh_token", refreshToken, cookieOptions);      res.json({ accessToken });    } catch (err) {      next(err);    }  });  router.post("/logout", async (req, res, next) => {    try {      await auth.logout(req.cookies?.refresh_token as string | undefined);      res.clearCookie("refresh_token", { path: cookieOptions.path });      res.status(204).end();    } catch (err) {      next(err);    }  });  return router;}

Because the cookie uses SameSite=Strict and a narrow path, it is only sent to /auth/refresh from your own site, which greatly reduces CSRF exposure.

The routes call next(err), so register one error handler after them. It maps known errors to status codes and avoids leaking internals:

ts
// src/errors.tsimport type { NextFunction, Request, Response } from "express";import { ZodError } from "zod";import { AuthError } from "./auth/auth.service";export function errorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction) {  if (err instanceof AuthError) return res.status(err.status).json({ error: err.message });  if (err instanceof ZodError) return res.status(400).json({ error: "Invalid request", details: err.flatten().fieldErrors });  console.error(err); // log details server-side only  res.status(500).json({ error: "Internal server error" });}// app.use("/auth", authRoutes(authService));// app.use(errorHandler);

Step 6: Authenticate requests and check roles

ts
// src/auth/middleware.tsimport type { NextFunction, Request, Response } from "express";import { verifyAccessToken, type AccessClaims } from "./tokens";declare module "express-serve-static-core" {  interface Request {    user?: { id: string; role: AccessClaims["role"] };  }}export function requireAuth(req: Request, res: Response, next: NextFunction) {  const header = req.header("authorization");  const token = header?.startsWith("Bearer ") ? header.slice(7) : undefined;  if (!token) return res.status(401).json({ error: "Missing access token" });  try {    const claims = verifyAccessToken(token);    req.user = { id: claims.sub, role: claims.role };    next();  } catch {    // Expired and invalid tokens both end up here; clients should call /auth/refresh.    res.status(401).json({ error: "Invalid or expired access token" });  }}export const requireRole =  (...roles: AccessClaims["role"][]) =>  (req: Request, res: Response, next: NextFunction) =>    req.user && roles.includes(req.user.role)      ? next()      : res.status(403).json({ error: "Forbidden" });

Use them together:

ts
app.get("/api/me", requireAuth, (req, res) => res.json({ user: req.user }));app.delete("/api/users/:id", requireAuth, requireRole("admin"), deleteUserHandler);

Step 7: Client behavior

On the client, keep the access token in memory (a module variable or state), send it as Authorization: Bearer, and when a request fails with 401, call /auth/refresh once and retry. If the refresh fails, send the user to log in. Because the access token lives only in memory, a page reload calls /auth/refresh first to get a new one.

Security checklist

  • Secrets: at least 32 random bytes, from environment or a secrets manager, rotated periodically.
  • Algorithms: pinned in verify, never taken from the token header.
  • Claims: validate iss, aud and exp.
  • Payload: never include passwords or personal data. It is readable by anyone holding the token.
  • Transport: HTTPS only; set Secure on cookies and Strict-Transport-Security headers.
  • Brute force: rate limit /auth/login and /auth/refresh, and consider temporary lockouts.
  • Logout and password change: revoke the user's refresh token families.
  • Errors: return generic messages for failed logins.

Performance considerations

Verifying an HS256 token is a fast, local operation, so access-token checks add almost no latency. Refresh calls hit the database, but they happen at most once per access-token lifetime per user. Index tokenHash and familyId, and periodically delete expired records.

Testing the flow

ts
// src/auth/auth.test.tsimport request from "supertest";import { createApp } from "../app";describe("auth", () => {  const app = createApp(); // build the app with in-memory fakes for users and refresh tokens  it("rejects a wrong password with a generic message", async () => {    const res = await request(app).post("/auth/login").send({ email: "a@example.com", password: "wrong-password" });    expect(res.status).toBe(401);    expect(res.body.error).toBe("Invalid email or password");  });  it("returns an access token and an httpOnly refresh cookie", async () => {    const res = await request(app).post("/auth/login").send({ email: "a@example.com", password: "correct-password" });    expect(res.status).toBe(200);    expect(res.body.accessToken).toEqual(expect.any(String));    const cookie = (res.headers["set-cookie"] as unknown as string[])[0]!;    expect(cookie).toContain("HttpOnly");    expect(cookie).toContain("SameSite=Strict");  });  it("blocks protected routes without a token", async () => {    const res = await request(app).get("/api/me");    expect(res.status).toBe(401);  });  it("detects refresh token reuse", async () => {    const login = await request(app).post("/auth/login").send({ email: "a@example.com", password: "correct-password" });    const cookie = (login.headers["set-cookie"] as unknown as string[])[0]!;    await request(app).post("/auth/refresh").set("Cookie", cookie).expect(200);    await request(app).post("/auth/refresh").set("Cookie", cookie).expect(401); // old token reused  });});

Also test expiry by signing a token with a past exp, and test that a token signed with the wrong algorithm or secret is rejected.

Troubleshooting

SymptomLikely cause
jwt malformedMissing Bearer prefix or an empty header
invalid signatureDifferent secret between signer and verifier, or key rotated
jwt expired right after loginServer clock skew or a TTL set in the wrong unit
Cookie never arrivesMissing credentials: "include" on fetch, Secure over plain HTTP, or wrong path
Users logged out randomlyRefresh rotation race: two tabs refreshed at once
req.cookies is undefinedcookie-parser not registered before the routes

The rotation race is worth a design decision: either serialize refresh calls on the client (a single in-flight refresh shared by all requests) or allow a short grace window on the server for the previous token.

Best practices

  • Keep access tokens short and refresh tokens revocable.
  • Hash everything you store: passwords with Argon2id, refresh tokens with SHA-256.
  • Validate all input with a schema library.
  • Rate limit authentication endpoints.
  • Log authentication events (success, failure, reuse detection) without logging secrets.
  • Prefer an established identity provider when the requirements grow beyond email and password: social login, MFA and account recovery are easy to underestimate.

Conclusion

Secure JWT authentication is less about the token format and more about the system around it: short lifetimes, pinned algorithms, httpOnly cookies, hashed storage and rotation with reuse detection. The code above is intentionally small, and each piece maps to a specific attack it prevents. Start with this structure, add rate limiting and monitoring, and revisit the design when you need single sign-on or multi-factor authentication.

Frequently asked questions

+โˆ’Where should I store JWTs in a browser app?

Keep the refresh token in an httpOnly, Secure, SameSite cookie so JavaScript cannot read it, and keep the short-lived access token in memory. Avoid localStorage for tokens: any XSS vulnerability can read it.

+โˆ’How long should an access token live?

Short: commonly 5 to 15 minutes. A short lifetime limits the damage of a leaked token, and the refresh token silently replaces it. The right value depends on your risk tolerance and how costly a refresh is.

+โˆ’What is refresh token rotation?

Each time a refresh token is used, the server issues a new one and invalidates the old one. If an old token is presented again, the server treats it as theft and revokes the whole token family.

+โˆ’Should I use HS256 or RS256?

HS256 uses one shared secret and is fine when one service both signs and verifies tokens. Use an asymmetric algorithm such as RS256 or EdDSA when other services must verify tokens without being able to create them.

+โˆ’Can I revoke a JWT?

A stateless access token cannot be revoked before it expires, which is why it should be short-lived. Refresh tokens are stored server-side (hashed), so those can be revoked immediately, and you can keep a small denylist for emergencies.

+โˆ’Do I need CSRF protection if I use cookies?

Yes, for cookie-authenticated requests that change state. Use SameSite cookies (Lax or Strict), scope the refresh cookie to its endpoint, and add a CSRF token or custom header check where cross-site requests are possible.

+โˆ’bcrypt or argon2 for passwords?

Both are acceptable. Argon2id is the current recommendation from OWASP when available; bcrypt remains a solid, widely supported choice. Never use fast hashes like SHA-256 for passwords.

Further reading

  • datatracker.ietf.org/doc/html/rfc7519
  • cheatsheetseries.owasp.org/

Hamza Janzaib

Full-Stack Developer based in Karachi, Pakistan. Building web apps, APIs and cloud infrastructure. About me


Related articles

Next.js, React & TypeScriptNovember 28, 202613 min readIntermediate

Handling Authentication and Protected Routes in Next.js

Optimistic checks in proxy, real checks next to the data: a layered approach to protecting routes.

Backend, Node.js, NestJS & APIsNovember 28, 202612 min readBeginner

Building REST APIs with Proper Validation and Error Handling

Validate once at the boundary, throw typed errors, and return one consistent error shape everywhere.

AWS, Deployment & DevOpsNovember 28, 202618 min readIntermediate

Deploying a Node.js Application on AWS EC2 From Scratch

The full path from an empty EC2 instance to a Node.js app behind Nginx and HTTPS, with troubleshooting.

Built by Hamza Janzaib