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

@avi00/express-idempotency

v1.0.0

Published

Express middleware to prevent duplicate request processing using idempotency keys

Downloads

85

Readme

express-idempotency

A lightweight, robust, and type-safe Express middleware to prevent duplicate request processing (e.g. double-charges on payments) using Idempotency Keys.

Built with strict adherence to SOLID, DRY, and KISS principles. Features zero unnecessary dependencies.

Features

  • Middleware Pipeline (Chain of Responsibility): Drop-in Express middleware.
  • Storage Backend (Strategy Pattern): Easily swap storage engines. Comes out of the box with:
    • MemoryStore: High-performance in-memory cache using JS Map and a custom Least Recently Used (LRU) eviction algorithm.
    • RedisStore: Atomic locking and caching using Redis (compatible with ioredis or any Redis-like client).
  • Response Capture (Decorator Pattern): Intercepts res.json(), res.send(), and res.end() to capture response status, headers, and body automatically without modifying route code.
  • Fingerprinting: Prevent key collisions across routes/users by hashing the Idempotency-Key along with the HTTP method, route path, and an optional userId.
  • Fault-Tolerant: Safely deletes locks and releases keys on unhandled errors, client aborts, or server error statuses (5xx) so clients can safely retry.

Installation

npm install express-idempotency
# If you are using RedisStore, install ioredis:
npm install ioredis

Usage

1. In-Memory Store (LRU)

import express from 'express';
import { idempotency } from 'express-idempotency';
import { MemoryStore } from 'express-idempotency/stores';

const app = express();

app.use(idempotency({
  store: new MemoryStore({ maxSize: 1000 }),
  ttlSeconds: 86400, // Cache for 24 hours
  enforceHeader: false, // If true, throws 400 Bad Request if Idempotency-Key is missing
}));

app.post('/payments', (req, res) => {
  res.status(201).json({ success: true, txnId: 'txn_12345' });
});

2. Redis Store (Using Connection String)

To use Redis, configure your client using your connection string, and pass the client instance to RedisStore. This allows you to configure timeouts, TLS, connection pools, and reuse the Redis connection across your application:

import express from 'express';
import { idempotency } from 'express-idempotency';
import { RedisStore } from 'express-idempotency/stores';
import Redis from 'ioredis';

const app = express();

// Initialize ioredis with your Redis connection string (URI)
const redisClient = new Redis('redis://:your_password@localhost:6379/0');

app.use(idempotency({
  store: new RedisStore(redisClient, { keyPrefix: 'my-app:' }),
  ttlSeconds: 86400, // Cache for 24 hours
  // Tie idempotency keys to user accounts to prevent key collisions across users:
  getUserId: (req) => req.headers['x-user-id'] as string | undefined,
}));

app.post('/orders', (req, res) => {
  res.json({ orderId: 'ord_98765', status: 'created' });
});

API Reference

idempotency(options)

Middleware creator. Takes the following options:

| Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | store | IIdempotencyStore | Required | Storage strategy to use (MemoryStore or RedisStore). | | ttlSeconds | number | 86400 (24h) | Time-to-live in seconds for cached responses and locks. | | headerName | string | 'Idempotency-Key' | Header to inspect for the idempotency key. | | enforceHeader | boolean | false | If true, returns 400 Bad Request if the header is missing. | | getUserId | (req) => string \| Promise<string> | undefined | Extracts user ID to lock request scope to a specific user. | | shouldCache | (res) => boolean | status < 500 | Predicate checking if a status code should be cached (5xx is not cached by default). | | errorMessage | string | 'Request in progress' | Custom message returned for concurrent conflict requests (409). |

Custom Storage Strategy

You can implement your own strategy by implementing the IIdempotencyStore interface:

import { IIdempotencyStore, IdempotencyRecord } from 'express-idempotency';

class CustomStore implements IIdempotencyStore {
  async get(key: string): Promise<IdempotencyRecord | null> {
    // get from DB
  }
  async set(key: string, record: IdempotencyRecord, ttlSeconds: number): Promise<void> {
    // save to DB
  }
  async setLock(key: string, ttlSeconds: number): Promise<boolean> {
    // atomically set lock (status: 'started') and return true if key did not exist
  }
  async delete(key: string): Promise<void> {
    // delete key
  }
}

License

MIT