typescriptintermediate

JWT Verify Middleware

Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.

typescript
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.