typescriptadvanced
Idempotency Key Middleware
Prevents duplicate request processing by caching responses keyed by the Idempotency-Key header.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Request, Response, NextFunction } from 'express';
const store = new Map<string, { status: number; body: unknown }>();
export function idempotencyMiddleware(req: Request, res: Response, next: NextFunction) {
if (req.method !== 'POST' && req.method !== 'PUT') return next();
const key = req.headers['idempotency-key'] as string;
if (!key) return next();
const cached = store.get(key);
if (cached) {
res.setHeader('X-Idempotent-Replayed', 'true');
return res.status(cached.status).json(cached.body);
}
const originalJson = res.json.bind(res);
res.json = function (body: unknown) {
store.set(key, { status: res.statusCode, body });
setTimeout(() => store.delete(key), 24 * 60 * 60 * 1000);
return originalJson(body);
};
next();
}Use Cases
- Payment processing
- Preventing duplicate orders
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
HTTP Client with Axios Interceptors
Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.
Best for: Consuming third-party APIs
#axios#http
typescriptintermediate
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
#nodejs#shutdown
typescriptintermediate
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
#nodejs#validation
typescriptintermediate
Node.js Token Bucket Rate Limiter
Implement an in-memory token bucket rate limiter for controlling API request throughput.
Best for: Protecting APIs from abuse and DDoS
#nodejs#rate-limiting