Node.js JWT Auth with TypeScript

Implement JWT authentication in a Node.js Express server with TypeScript, including token signing, verification middleware, refresh token rotation, and.

TypescriptNodeAuth Jwt

Code

snippet
import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';

declare module 'express' {
  interface Request { userId?: string;}
}

export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token' });
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string };
    req.userId = payload.sub;
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

How the snippet works

One way to read it: the function authMiddleware, doing all the work.

Request, Response, NextFunction are the only symbols borrowed from jsonwebtoken — the coupling is explicit and narrow.

Configuration comes from the environment — it reads JWT_SECRET, so the same code switches behavior between environments without edits.

What to watch for

  • Dependency check: jsonwebtoken and express — not built-in, must be present in the project.
  • The guard !token short-circuits the flow with an early return when its condition holds.

Using it

The entry-point signature is export function authMiddleware(req: Request, res: Response, next: NextFunction)

Import authMiddleware from the file and call it — the rest of the code is implementation detail.

Key statements

if (!token) return res.status(401).json({ error: 'No token' });
const token = req.headers.authorization?.split(' ')[1];

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `jsonwebtoken` and `express` must be present in the project or the import fails at load time.