typescriptbeginner
Structured Request Logger Middleware
Express middleware that logs request/response details as structured JSON with timing information.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
export function requestLogger(req: Request, res: Response, next: NextFunction) {
const start = Date.now();
res.on('finish', () => {
const log = {
timestamp: new Date().toISOString(),
method: req.method,
path: req.originalUrl,
status: res.statusCode,
duration: `${Date.now() - start}ms`,
userAgent: req.headers['user-agent'],
ip: req.ip,
};
console.log(JSON.stringify(log));
});
next();
}Use Cases
- API monitoring
- Debugging and troubleshooting
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Request ID Tracing Middleware
Express middleware that generates or forwards X-Request-Id headers for distributed tracing.
Best for: Distributed tracing
#express#tracing
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