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.
Code
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:
jsonwebtokenandexpress— not built-in, must be present in the project. - The guard
!tokenshort-circuits the flow with an earlyreturnwhen 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
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.