npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@reaatech/idempotency-middleware-express

v1.0.0

Published

Express middleware for @reaatech/idempotency-middleware

Readme

@reaatech/idempotency-middleware-express

npm version License: MIT CI

Express middleware for @reaatech/idempotency-middleware. Adds idempotency to Express route handlers by caching responses keyed by the Idempotency-Key header. Supports Express 4 and 5.

Installation

npm install @reaatech/idempotency-middleware-express
# or
pnpm add @reaatech/idempotency-middleware-express

express must already be installed in your project.

Feature Overview

  • Route-level idempotency — add app.use(idempotentExpress(adapter)) before your routes
  • Automatic body capture — monkey-patches res.json() and res.send() to capture response bodies for caching
  • res.end() support — handles 204 No Content and other body-less responses gracefully
  • Client disconnect handlingclose event releases the lock without persisting incomplete responses
  • Custom error handler — pluggable errorHandler callback for idempotency errors
  • Custom key extractiongetKey option for extracting the idempotency key from any part of the request

Quick Start

import express from 'express';
import { MemoryAdapter } from '@reaatech/idempotency-middleware';
import { idempotentExpress } from '@reaatech/idempotency-middleware-express';

const adapter = new MemoryAdapter();
await adapter.connect();

const app = express();
app.use(express.json());
app.use(idempotentExpress(adapter));

app.post('/charges', (req, res) => {
  // If retried with the same Idempotency-Key header,
  // this handler is not called again — the cached 201 is returned.
  res.status(201).json({ id: 1, amount: req.body.amount });
});

app.listen(3000);
curl -XPOST http://localhost:3000/charges \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: abc-123" \
  -d '{"amount": 100}'
# → 201 { "id": 1, "amount": 100 }

# Same key, same response — handler not re-executed
curl -XPOST http://localhost:3000/charges \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: abc-123" \
  -d '{"amount": 200}'
# → 201 { "id": 1, "amount": 100 }

API Reference

idempotentExpress(storage, config?)

import { idempotentExpress } from '@reaatech/idempotency-middleware-express';

app.use(idempotentExpress(adapter, {
  ttl: 60_000,
  methods: ['POST', 'PUT'],
}));

Parameters

| Param | Type | Description | |---|---|---| | storage | StorageAdapter | The storage adapter to use (from @reaatech/idempotency-middleware or any adapter package) | | config | ExpressIdempotencyConfig | Configuration options (see below) |

ExpressIdempotencyConfig

Extends IdempotencyConfig with one additional option:

| Property | Type | Description | |---|---|---| | errorHandler | (err: IdempotencyError, req: Request, res: Response, next: NextFunction) => void | Custom handler for idempotency errors |

All options from IdempotencyConfig are also supported: headerName, ttl, methods, getKey, shouldCache, varyHeaders, includeBodyInKey, maxKeyLength, lockTimeout, lockTtl, lockPollInterval.

Request Flow

For each matching HTTP method request:

  1. Key extraction — uses getKey if provided, otherwise reads config.headerName (default "Idempotency-Key") from request headers
  2. No key → pass through — requests without an idempotency key bypass the middleware entirely
  3. Cache check — generates a cache key and checks storage for an existing response
  4. Cache hit — replays the cached status code, headers, and body directly
  5. Cache miss — acquires a distributed lock, patches res.json() / res.send(), passes control to next()
  6. Response capture — on finish event, caches the captured body + status code + headers
  7. Client abort — on close event (before finish), releases the lock without persisting

Response Capture

The middleware patches res.json() and res.send() to intercept the response body. All response headers are captured via res.getHeaders(). On the next request with the same idempotency key, the exact status code, headers, and body are replayed:

// Original request: res.status(201).json({ id: 1 })
// Cached: { statusCode: 201, headers: { 'content-type': 'application/json' }, response: { id: 1 } }
// Reply: res.status(201).set(headers).send(body)

Body-less responses (res.status(204).end()) are handled correctly — no body is captured and the cached response replays 204 without a body.

Usage Patterns

Custom Error Handling

app.use(idempotentExpress(adapter, {
  ttl: 60_000,
  errorHandler: (err, req, res, next) => {
    if (err.code === 'KEY_REQUIRED') {
      res.status(400).json({ error: 'Missing idempotency key' });
    } else if (err.isRecoverable()) {
      res.status(503).json({ error: 'Temporarily unavailable, please retry' });
    } else {
      res.status(err.getStatusCode()).json({ error: err.message });
    }
  },
}));

Custom Key Extraction

app.use(idempotentExpress(adapter, {
  getKey: (req) => req.headers['x-custom-idempotency-key'] as string,
}));

Selective Caching

app.use(idempotentExpress(adapter, {
  shouldCache: (body) => {
    // Don't cache responses with transient data
    if (body && typeof body === 'object' && 'transient' in body) return false;
    return true;
  },
}));

Vary Headers (Content Negotiation)

app.use(idempotentExpress(adapter, {
  varyHeaders: ['Accept-Language', 'Accept-Encoding'],
}));
// Same idempotency key, different Accept-Language → different cache keys

Distributed Redis Backend

import { Redis } from 'ioredis';
import { RedisAdapter } from '@reaatech/idempotency-middleware-adapter-redis';
import { idempotentExpress } from '@reaatech/idempotency-middleware-express';

const redis = new Redis('redis://localhost:6379');
const storage = new RedisAdapter(redis);
await storage.connect();

const app = express();
app.use(express.json());
app.use(idempotentExpress(storage, { ttl: 3_600_000 }));

Related Packages

License

MIT