typescriptadvanced

Idempotency Key Middleware

Prevents duplicate request processing by caching responses keyed by the Idempotency-Key header.

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