typescriptbeginner
Request Timeout Middleware
Express middleware that aborts requests exceeding a configurable time limit with 408 status.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptbeginner
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Best for: Express route error handling
#express#async
typescriptbeginner
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
Best for: API input validation
#express#zod