JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
interface AuthRequest extends Request {
user?: jwt.JwtPayload;
}
export function verifyJwt(secret: string) {
return (req: AuthRequest, res: Response, next: NextFunction) => {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing bearer token' });
}
try {
const token = header.slice(7);
const decoded = jwt.verify(token, secret) as jwt.JwtPayload;
req.user = decoded;
next();
} catch (err) {
const message =
err instanceof jwt.TokenExpiredError
? 'Token expired'
: 'Invalid token';
return res.status(403).json({ error: message });
}
};
}Sponsored
Auth0 — Identity platform for developers
Use Cases
- REST API authentication
- Protecting private endpoints
- Role-based access control
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
JWT Refresh Token Rotation
Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.