typescriptbeginner

Request Timeout Middleware

Express middleware that aborts requests exceeding a configurable time limit with 408 status.

typescript
import { Request, Response, NextFunction } from 'express';

export function requestTimeout(ms = 30_000) {
  return (req: Request, res: Response, next: NextFunction) => {
    const timer = setTimeout(() => {
      if (!res.headersSent) {
        res.status(408).json({ error: 'Request timeout' });
      }
    }, ms);

    res.on('finish', () => clearTimeout(timer));
    res.on('close', () => clearTimeout(timer));
    next();
  };
}

Use Cases

  • Preventing hanging requests
  • API reliability

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.