Skip to content

@nestarc/idempotency API reference ​

Register IdempotencyModule, apply the interceptor and route decorators, configure endpoint identity and replay policy, and use dependency-free memory storage and public contracts.

Browse all @nestarc/idempotency import paths.

Classes ​

IdempotencyInterceptor ​

Defined in: src/idempotency.interceptor.ts:117

The core idempotency interceptor.

Reads @Idempotent() metadata off the handler, extracts the configured idempotency header, computes a request body fingerprint, and dispatches the storage state machine: replay COMPLETED, conflict on PROCESSING, mismatch on differing fingerprint, otherwise lock + delegate + capture response under token-based compare-and-set.

Implements the IETF draft httpapi-idempotency-key-header-07 semantics for 400 / 409 / 422 responses.

Implements ​

  • NestInterceptor

Constructors ​

Constructor ​
ts
new IdempotencyInterceptor(
   reflector,
   storage,
   moduleOptions): IdempotencyInterceptor;

Defined in: src/idempotency.interceptor.ts:120

Parameters ​
ParameterType
reflectorReflector
storageIdempotencyStorage
moduleOptionsIdempotencyOptions
Returns ​

IdempotencyInterceptor

Methods ​

intercept() ​
ts
intercept(context, next): Observable<unknown>;

Defined in: src/idempotency.interceptor.ts:136

Method to implement a custom interceptor.

Parameters ​
ParameterTypeDescription
contextExecutionContextan ExecutionContext object providing methods to access the route handler and class about to be invoked.
nextCallHandlera reference to the CallHandler, which provides access to an Observable representing the response stream from the route handler.
Returns ​

Observable<unknown>

Implementation of ​
ts
NestInterceptor.intercept

IdempotencyModule ​

Defined in: src/idempotency.module.ts:35

NestJS dynamic module exposing the IdempotencyInterceptor and the configured IdempotencyStorage.

The module does not auto-register the interceptor as APP_INTERCEPTOR — consumers opt in via one of three patterns:

  1. App-global: providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }]
  2. Controller-scoped: @UseInterceptors(IdempotencyInterceptor) on the class
  3. Method-scoped: @UseInterceptors(IdempotencyInterceptor) on the handler

The module is registered as global by default so consumers can wire any of the three patterns without re-importing it everywhere.

Constructors ​

Constructor ​
ts
new IdempotencyModule(): IdempotencyModule;
Returns ​

IdempotencyModule

Methods ​

forRoot() ​
ts
static forRoot(options): DynamicModule;

Defined in: src/idempotency.module.ts:36

Parameters ​
ParameterType
optionsIdempotencyOptions
Returns ​

DynamicModule

forRootAsync() ​
ts
static forRootAsync(options): DynamicModule;

Defined in: src/idempotency.module.ts:58

Parameters ​
ParameterType
optionsIdempotencyAsyncOptions
Returns ​

DynamicModule


MemoryStorage ​

Defined in: src/storage/memory.storage.ts:29

In-memory implementation of IdempotencyStorage.

Backed by a Map with per-entry setTimeout expirations. Suitable for tests and single-instance development. Not safe for production: state is lost on restart and not shared across processes — two replicas would each enforce idempotency independently, letting duplicates slip through.

Implements ​

Constructors ​

Constructor ​
ts
new MemoryStorage(): MemoryStorage;
Returns ​

MemoryStorage

Methods ​

complete() ​
ts
complete(
   key,
   token,
   response,
ttlSeconds): Promise<MutateResult>;

Defined in: src/storage/memory.storage.ts:61

Transitions a PROCESSING record to COMPLETED and stores the captured response, but ONLY if the record is unexpired and its token matches the caller's. Returns 'stale' for missing/expired records, token mismatches, and an already COMPLETED record (including the same token). A stale operation must not overwrite a response or refresh TTL.

On 'ok', implementations must refresh the TTL to ttlSeconds.

Parameters ​
ParameterTypeDescription
keystring-
tokenstring-
responseCompleteResponse-
ttlSecondsnumbercompleted record lifetime, an integer in [1, 2_147_483_647] seconds
Returns ​

Promise<MutateResult>

Throws ​

RangeError if ttlSeconds is invalid, before ownership or state checks

Implementation of ​

IdempotencyStorage.complete

create() ​
ts
create(
   key,
   fingerprint,
ttlSeconds): Promise<CreateResult>;

Defined in: src/storage/memory.storage.ts:36

Atomically creates a PROCESSING record. On success, returns an opaque token that the caller MUST pass back to complete() / delete(). An expired record is absent for NX purposes, regardless of physical cleanup.

Parameters ​
ParameterTypeDescription
keystringthe idempotency key from the client header (already scoped by the interceptor to include endpoint identity)
fingerprintstring | undefinedSHA-256 of the request body, or undefined if fingerprinting is off
ttlSecondsnumberlifetime of the lock, an integer in [1, 2_147_483_647] seconds
Returns ​

Promise<CreateResult>

Throws ​

RangeError if ttlSeconds is invalid, before NX or expiry checks

Implementation of ​

IdempotencyStorage.create

delete() ​
ts
delete(key, token): Promise<MutateResult>;

Defined in: src/storage/memory.storage.ts:100

Removes a record, but ONLY if the caller's token matches. Returns 'ok' if the record was removed OR was absent/expired (idempotent cleanup), and 'stale' only if a DIFFERENT record (with a different token) is currently stored and unexpired under this key. Expired physical rows may remain for later cleanup; delete success does not promise immediate physical removal.

Parameters ​
ParameterType
keystring
tokenstring
Returns ​

Promise<MutateResult>

Implementation of ​

IdempotencyStorage.delete

get() ​
ts
get(key): Promise<IdempotencyRecord | null>;

Defined in: src/storage/memory.storage.ts:32

Fetches a record by key. Returns null if the key does not exist or has expired.

Parameters ​
ParameterType
keystring
Returns ​

Promise<IdempotencyRecord | null>

Implementation of ​

IdempotencyStorage.get

onModuleDestroy() ​
ts
onModuleDestroy(): Promise<void>;

Defined in: src/storage/memory.storage.ts:117

Lifecycle hook: clear all pending eviction timers when the module is torn down. Prevents leaked timers from keeping the Node event loop alive in long test runs.

Returns ​

Promise<void>

Implementation of ​
ts
OnModuleDestroy.onModuleDestroy

Interfaces ​

CompleteResponse ​

Defined in: src/interfaces/idempotency-storage.interface.ts:6

The response payload captured by the interceptor and persisted by storage.

Properties ​

body? ​
ts
optional body?: string;

Defined in: src/interfaces/idempotency-storage.interface.ts:16

Opaque replay payload. Store and return this string unchanged; do not JSON.parse/stringify or otherwise normalize it. The interceptor writes a versioned envelope, including for empty HTTP bodies. Optional for storage callers and older records; missing/legacy payloads are not replayed.

headers? ​
ts
optional headers?: Record<string, string>;

Defined in: src/interfaces/idempotency-storage.interface.ts:19

Lowercase HTTP response headers captured for replay.

statusCode ​
ts
statusCode: number;

Defined in: src/interfaces/idempotency-storage.interface.ts:8

HTTP status code emitted by the original handler.


CreateResult ​

Defined in: src/interfaces/idempotency-storage.interface.ts:33

Return shape of IdempotencyStorage.create.

acquired === true means this caller successfully created a new PROCESSING record and was given an opaque token that uniquely identifies that record. The caller MUST pass this token back to complete() / delete() so the storage can verify it still owns the record before mutating it.

acquired === false means a record already existed (NX semantics). No token is issued in this case.

Properties ​

acquired ​
ts
acquired: boolean;

Defined in: src/interfaces/idempotency-storage.interface.ts:34

token? ​
ts
optional token?: string;

Defined in: src/interfaces/idempotency-storage.interface.ts:35


IdempotencyAsyncOptions ​

Defined in: src/interfaces/idempotency-options.interface.ts:215

Async configuration passed to IdempotencyModule.forRootAsync. Mirrors the standard NestJS async-module pattern (useFactory / useClass / useExisting).

Extends ​

  • Pick<ModuleMetadata, "imports">

Properties ​

imports? ​
ts
optional imports?: (
  | DynamicModule
  | Type<any>
  | Promise<DynamicModule>
  | ForwardReference<any>)[];

Defined in: node_modules/@nestjs/common/interfaces/modules/module-metadata.interface.d.ts:18

Optional list of imported modules that export the providers which are required in this module.

Inherited from ​
ts
Pick.imports

inject? ​
ts
optional inject?: any[];

Defined in: src/interfaces/idempotency-options.interface.ts:221

isGlobal? ​
ts
optional isGlobal?: boolean;

Defined in: src/interfaces/idempotency-options.interface.ts:222

useClass? ​
ts
optional useClass?: Type<IdempotencyOptionsFactory>;

Defined in: src/interfaces/idempotency-options.interface.ts:217

useExisting? ​
ts
optional useExisting?: Type<IdempotencyOptionsFactory>;

Defined in: src/interfaces/idempotency-options.interface.ts:216

useFactory? ​
ts
optional useFactory?: (...args) =>
  | IdempotencyOptions
| Promise<IdempotencyOptions>;

Defined in: src/interfaces/idempotency-options.interface.ts:218

Parameters ​
ParameterType
...argsany[]
Returns ​

| IdempotencyOptions | Promise<IdempotencyOptions>


IdempotencyEvent ​

Defined in: src/interfaces/idempotency-options.interface.ts:82

Properties ​

error? ​
ts
optional error?: IdempotencyEventError;

Defined in: src/interfaces/idempotency-options.interface.ts:89

keyHash ​
ts
keyHash: string;

Defined in: src/interfaces/idempotency-options.interface.ts:85

SHA-256 of the v1 encoded storage key; not a metric label or encryption.

namespace ​
ts
namespace: string;

Defined in: src/interfaces/idempotency-options.interface.ts:87

S3 v1 identity + endpoint namespace hash, independent of the raw key.

outcome ​
ts
outcome: IdempotencyOutcome;

Defined in: src/interfaces/idempotency-options.interface.ts:83

statusCode? ​
ts
optional statusCode?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:88


IdempotencyFingerprintInput ​

Defined in: src/interfaces/idempotency-options.interface.ts:43

Properties ​

body ​
ts
body: unknown;

Defined in: src/interfaces/idempotency-options.interface.ts:47

context ​
ts
context: ExecutionContext;

Defined in: src/interfaces/idempotency-options.interface.ts:44

defaultFingerprint ​
ts
defaultFingerprint: () => string | undefined;

Defined in: src/interfaces/idempotency-options.interface.ts:48

Returns ​

string | undefined

key ​
ts
key: string;

Defined in: src/interfaces/idempotency-options.interface.ts:45

scope ​
ts
scope: string;

Defined in: src/interfaces/idempotency-options.interface.ts:46


IdempotencyObservabilityOptions ​

Defined in: src/interfaces/idempotency-options.interface.ts:92

Properties ​

exposeStatusHeaders? ​
ts
optional exposeStatusHeaders?: boolean;

Defined in: src/interfaces/idempotency-options.interface.ts:96

Defaults to true. These headers are generated afresh, never replayed.

onEvent? ​
ts
optional onEvent?: (event) => void | Promise<void>;

Defined in: src/interfaces/idempotency-options.interface.ts:94

Best effort, not awaited. Throws/rejections never change request handling.

Parameters ​
ParameterType
eventIdempotencyEvent
Returns ​

void | Promise<void>


IdempotencyOptions ​

Defined in: src/interfaces/idempotency-options.interface.ts:102

Module-level configuration passed to IdempotencyModule.forRoot.

Properties ​

fingerprint? ​
ts
optional fingerprint?:
  | boolean
  | IdempotencyFingerprintResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:167

When true, the interceptor computes a SHA-256 fingerprint of the request body and verifies it on subsequent requests. Pass a resolver function to provide an application-specific semantic fingerprint. A mismatch produces HTTP 422.

Default ​
ts
true

headerName? ​
ts
optional headerName?: string;

Defined in: src/interfaces/idempotency-options.interface.ts:141

The HTTP header name carrying one raw opaque key string. Repeated fields, arrays and comma-joined values are rejected. Quotes are literal; this is not a Structured Field String parser.

Default ​
ts
'Idempotency-Key'

isGlobal? ​
ts
optional isGlobal?: boolean;

Defined in: src/interfaces/idempotency-options.interface.ts:199

When true, the module is registered as a global module (no need to import it into every consumer module).

Default ​
ts
true

keyResolver? ​
ts
optional keyResolver?: IdempotencyKeyResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:149

Optional application-level idempotency key resolver. When configured, its return value is used instead of reading the configured header. Only undefined means missing. Invalid strings/non-string results produce 400 even when required:false. Commas are allowed in resolver keys.

maxKeyLength? ​
ts
optional maxKeyLength?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:158

Maximum accepted idempotency key length, in UTF-8 bytes. Must be a positive safe integer. Empty/blank strings, controls and unpaired surrogates are rejected. Strings are not trimmed or Unicode-normalized by this package.

Default ​
ts
255

observability? ​
ts
optional observability?: IdempotencyObservabilityOptions;

Defined in: src/interfaces/idempotency-options.interface.ts:191

Optional operational hooks and client-visible status headers.

processingTtl? ​
ts
optional processingTtl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:132

Optional time-to-live for in-flight PROCESSING records, in seconds. When omitted, ttl is used for both processing locks and completed replay records. Per-handler @Idempotent({ processingTtl }) overrides this. Must be an integer from 1 through 2_147_483_647, like ttl.

Configure this only when you want stuck in-flight records to expire sooner than completed replay records. Values shorter than the endpoint's real processing time can allow duplicate execution.

replayHeaders? ​
ts
optional replayHeaders?: ReplayHeadersOption;

Defined in: src/interfaces/idempotency-options.interface.ts:186

Controls which response headers are captured and replayed.

true or undefined uses the conservative default allowlist. false disables header replay. A string array uses an explicit allowlist, still filtered through the unsafe header denylist.

Default ​
ts
true

scope? ​
ts
optional scope?: IdempotencyScope;

Defined in: src/interfaces/idempotency-options.interface.ts:174

How storage keys are namespaced. See IdempotencyScope.

Default ​
ts
'endpoint'

storage ​
ts
storage: IdempotencyStorage;

Defined in: src/interfaces/idempotency-options.interface.ts:108

The storage adapter instance to use. Construct it yourself (e.g. new MemoryStorage() or new RedisStorage({ host, port })) for full type-safe control over adapter wiring.

ttl? ​
ts
optional ttl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:120

Default time-to-live for idempotency records, in seconds. Per-handler @Idempotent({ ttl }) overrides this. Completed replay records use this TTL. In-flight PROCESSING records also use this TTL unless processingTtl is configured. Must be an integer from 1 through 2_147_483_647; otherwise a RangeError is emitted at request time before storage or handler execution.

Default ​
ts
86400 (24 hours)

IdempotencyOptionsFactory ​

Defined in: src/interfaces/idempotency-options.interface.ts:205

Factory contract for useClass / useExisting async registration paths.

Methods ​

createIdempotencyOptions() ​
ts
createIdempotencyOptions():
  | IdempotencyOptions
| Promise<IdempotencyOptions>;

Defined in: src/interfaces/idempotency-options.interface.ts:206

Returns ​

| IdempotencyOptions | Promise<IdempotencyOptions>


IdempotencyRecord ​

Defined in: src/interfaces/idempotency-record.interface.ts:14

The persisted shape of an idempotency record across all storage adapters.

Properties ​

createdAt ​
ts
createdAt: Date;

Defined in: src/interfaces/idempotency-record.interface.ts:54

When the record was first created by IdempotencyStorage.create().

Invariant: this field is IMMUTABLE over the lifetime of a record. complete() and any other mutation MUST preserve the original value. Storage adapters that rewrite createdAt on update are non-conformant and WILL break consumers who use it for monitoring (e.g. first-seen timestamps in metrics / audit trails).

expiresAt ​
ts
expiresAt: Date;

Defined in: src/interfaces/idempotency-record.interface.ts:61

When the record will be evicted by the storage adapter. Unlike createdAt, this field IS mutated on complete() when the adapter refreshes the TTL window to the new (typically longer) value.

fingerprint? ​
ts
optional fingerprint?: string;

Defined in: src/interfaces/idempotency-record.interface.ts:31

SHA-256 of the request body, used to detect a key being reused with a different payload (which produces HTTP 422 per the IETF draft). Undefined when fingerprinting is disabled.

key ​
ts
key: string;

Defined in: src/interfaces/idempotency-record.interface.ts:16

The exact value of the Idempotency-Key header from the original request.

responseBody? ​
ts
optional responseBody?: string;

Defined in: src/interfaces/idempotency-record.interface.ts:40

Opaque versioned replay payload; storage must preserve it unchanged.

responseHeaders? ​
ts
optional responseHeaders?: Record<string, string>;

Defined in: src/interfaces/idempotency-record.interface.ts:43

Lowercase HTTP response headers captured for replay.

status ​
ts
status: IdempotencyStatus;

Defined in: src/interfaces/idempotency-record.interface.ts:34

Current lifecycle state.

statusCode? ​
ts
optional statusCode?: number;

Defined in: src/interfaces/idempotency-record.interface.ts:37

Captured HTTP status code of the original handler response.

token ​
ts
token: string;

Defined in: src/interfaces/idempotency-record.interface.ts:24

Opaque token issued by IdempotencyStorage.create() that uniquely identifies THIS record across its lifetime. Used by complete() / delete() to compare-and-set so that a slow caller cannot clobber a newer caller's record after TTL eviction.


IdempotencyStorage ​

Defined in: src/interfaces/idempotency-storage.interface.ts:89

Pluggable storage contract for idempotency records.

Implementations must guarantee:

  1. Atomic creation (NX semantics) — two concurrent create() calls for the same key must result in exactly one acquired: true and one acquired: false.
  2. Token-based compare-and-set on complete() / delete() — a caller can only mutate a record whose stored token matches the token they received from their own create() call. This prevents the TTL-eviction race where a slow caller would otherwise clobber a newer caller's record.
  3. createdAt immutability — complete() and any other mutation MUST preserve the createdAt field of the original PROCESSING record. See IdempotencyRecord.createdAt.
  4. Logical expiry — a lease is absent at its storage deadline even when physical timer/sweep cleanup has not run. All operations share the same deadline; an expired owner cannot revive the lease with complete().
  5. Complete once — only a live PROCESSING record may become COMPLETED. Repeated/concurrent complete with the same token returns stale after the first success, preserving its response and retention deadline.
  6. TTL validation — create/complete accept integer seconds from 1 through 2_147_483_647 inclusive (including 30-day TTLs). Reject all other values with RangeError before any storage access or mutation, even for missing, expired, already completed, or differently owned records. This applies to direct adapter calls as well as calls through the interceptor.

Lifecycle ​

Storage adapters that hold external resources (Redis clients, DB connections, timers) SHOULD implement Nest's OnModuleDestroy hook so the resources are released when the host application shuts down. All built-in adapters (MemoryStorage, RedisStorage, PostgresStorage) do this — a custom adapter is free to opt in the same way.

A cross-adapter contract suite that exercises every requirement of this interface lives at test/support/shared-storage-contract.ts — new adapters should be plugged into it to guarantee LSP-level uniformity.

Methods ​

complete() ​
ts
complete(
   key,
   token,
   response,
ttlSeconds): Promise<MutateResult>;

Defined in: src/interfaces/idempotency-storage.interface.ts:119

Transitions a PROCESSING record to COMPLETED and stores the captured response, but ONLY if the record is unexpired and its token matches the caller's. Returns 'stale' for missing/expired records, token mismatches, and an already COMPLETED record (including the same token). A stale operation must not overwrite a response or refresh TTL.

On 'ok', implementations must refresh the TTL to ttlSeconds.

Parameters ​
ParameterTypeDescription
keystring-
tokenstring-
responseCompleteResponse-
ttlSecondsnumbercompleted record lifetime, an integer in [1, 2_147_483_647] seconds
Returns ​

Promise<MutateResult>

Throws ​

RangeError if ttlSeconds is invalid, before ownership or state checks

create() ​
ts
create(
   key,
   fingerprint,
ttlSeconds): Promise<CreateResult>;

Defined in: src/interfaces/idempotency-storage.interface.ts:106

Atomically creates a PROCESSING record. On success, returns an opaque token that the caller MUST pass back to complete() / delete(). An expired record is absent for NX purposes, regardless of physical cleanup.

Parameters ​
ParameterTypeDescription
keystringthe idempotency key from the client header (already scoped by the interceptor to include endpoint identity)
fingerprintstring | undefinedSHA-256 of the request body, or undefined if fingerprinting is off
ttlSecondsnumberlifetime of the lock, an integer in [1, 2_147_483_647] seconds
Returns ​

Promise<CreateResult>

Throws ​

RangeError if ttlSeconds is invalid, before NX or expiry checks

delete() ​
ts
delete(key, token): Promise<MutateResult>;

Defined in: src/interfaces/idempotency-storage.interface.ts:133

Removes a record, but ONLY if the caller's token matches. Returns 'ok' if the record was removed OR was absent/expired (idempotent cleanup), and 'stale' only if a DIFFERENT record (with a different token) is currently stored and unexpired under this key. Expired physical rows may remain for later cleanup; delete success does not promise immediate physical removal.

Parameters ​
ParameterType
keystring
tokenstring
Returns ​

Promise<MutateResult>

get() ​
ts
get(key): Promise<IdempotencyRecord | null>;

Defined in: src/interfaces/idempotency-storage.interface.ts:93

Fetches a record by key. Returns null if the key does not exist or has expired.

Parameters ​
ParameterType
keystring
Returns ​

Promise<IdempotencyRecord | null>


IdempotentMetadata ​

Defined in: src/interfaces/idempotency-options.interface.ts:271

The metadata shape persisted via SetMetadata by the Idempotent decorator. The enabled: true flag lets the interceptor distinguish "decorator applied with no overrides" from "no decorator at all".

Extends ​

Properties ​

enabled ​
ts
enabled: true;

Defined in: src/interfaces/idempotency-options.interface.ts:272

fingerprint? ​
ts
optional fingerprint?:
  | boolean
  | IdempotencyFingerprintResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:263

Override the module-level fingerprint setting for this handler.

Inherited from ​

IdempotentOptions.fingerprint

keyResolver? ​
ts
optional keyResolver?: IdempotencyKeyResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:253

Override the module-level key resolver for this handler.

Inherited from ​

IdempotentOptions.keyResolver

maxKeyLength? ​
ts
optional maxKeyLength?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:258

Override the module-level maximum key length for this handler.

Inherited from ​

IdempotentOptions.maxKeyLength

processingTtl? ​
ts
optional processingTtl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:248

Override the module-level processing TTL for this handler (in seconds). Must be an integer from 1 through 2_147_483_647.

Inherited from ​

IdempotentOptions.processingTtl

required? ​
ts
optional required?: boolean;

Defined in: src/interfaces/idempotency-options.interface.ts:236

When true, the Idempotency-Key header is mandatory and a missing header produces HTTP 400. When false, requests without the header pass through normally (no idempotency check).

Default ​
ts
true
Inherited from ​

IdempotentOptions.required

ttl? ​
ts
optional ttl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:242

Override the module-level TTL for this handler (in seconds). Must be an integer from 1 through 2_147_483_647.

Inherited from ​

IdempotentOptions.ttl


IdempotentOptions ​

Defined in: src/interfaces/idempotency-options.interface.ts:228

Per-handler overrides accepted by the Idempotent decorator.

Extended by ​

Properties ​

fingerprint? ​
ts
optional fingerprint?:
  | boolean
  | IdempotencyFingerprintResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:263

Override the module-level fingerprint setting for this handler.

keyResolver? ​
ts
optional keyResolver?: IdempotencyKeyResolver;

Defined in: src/interfaces/idempotency-options.interface.ts:253

Override the module-level key resolver for this handler.

maxKeyLength? ​
ts
optional maxKeyLength?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:258

Override the module-level maximum key length for this handler.

processingTtl? ​
ts
optional processingTtl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:248

Override the module-level processing TTL for this handler (in seconds). Must be an integer from 1 through 2_147_483_647.

required? ​
ts
optional required?: boolean;

Defined in: src/interfaces/idempotency-options.interface.ts:236

When true, the Idempotency-Key header is mandatory and a missing header produces HTTP 400. When false, requests without the header pass through normally (no idempotency check).

Default ​
ts
true

ttl? ​
ts
optional ttl?: number;

Defined in: src/interfaces/idempotency-options.interface.ts:242

Override the module-level TTL for this handler (in seconds). Must be an integer from 1 through 2_147_483_647.

Type Aliases ​

IdempotencyEventError ​

ts
type IdempotencyEventError =
  | {
  code: "storage_failure";
  operation: IdempotencyStorageOperation;
}
  | {
  code: "response_not_replayable";
};

Defined in: src/interfaces/idempotency-options.interface.ts:78

Package-owned diagnostics. Original thrown values are never included.


IdempotencyFingerprintResolver ​

ts
type IdempotencyFingerprintResolver = (input) => string | undefined | Promise<string | undefined>;

Defined in: src/interfaces/idempotency-options.interface.ts:55

Resolves the fingerprint used to detect reuse of the same idempotency key with a semantically different request.

Parameters ​

ParameterType
inputIdempotencyFingerprintInput

Returns ​

string | undefined | Promise<string | undefined>


IdempotencyKeyResolver ​

ts
type IdempotencyKeyResolver = (context) => string | undefined | Promise<string | undefined>;

Defined in: src/interfaces/idempotency-options.interface.ts:39

Resolves the idempotency key for a request. Use this when the stable key comes from a webhook event id, command id, or other application-level value instead of the configured HTTP header.

Parameters ​

ParameterType
contextExecutionContext

Returns ​

string | undefined | Promise<string | undefined>


IdempotencyOutcome ​

ts
type IdempotencyOutcome =
  | "created"
  | "replayed"
  | "conflict"
  | "mismatch"
  | "bypassed"
  | "stale"
  | "complete_error"
  | "storage_error";

Defined in: src/interfaces/idempotency-options.interface.ts:59


IdempotencyScope ​

ts
type IdempotencyScope = "endpoint" | "global" | ((context) => string | readonly string[]);

Defined in: src/interfaces/idempotency-options.interface.ts:27

How the interceptor derives the storage-key namespace from the request.

  • 'endpoint' (default) — scope by actual HTTP method + request path when available, falling back to Nest route metadata and then controller class + handler method name. Actual path parameters, duplicate/trailing slashes and percent encoding are preserved; query strings are excluded. No authenticated identity is inferred. Two different endpoints using the SAME Idempotency-Key value will NOT collide. Matches the IETF draft recommendation that the key be unique per (key, request URI) tuple.

  • 'global' — share keys across all identities and endpoints in the storage. Only use when all callers are authorized to share every replayed response. Storage keys are still versioned and encoded.

  • A synchronous function — ADD authenticated identity to the endpoint. Return a nonblank string or a nonempty array of nonblank strings, e.g. [req.user.tenantId, req.user.id]. Array boundaries are preserved. Guards must authenticate/authorize before this interceptor on every retry. Unlike 0.4, functions never replace the endpoint. All modes use the v1 key encoding with no legacy alias lookup. Upgrades require a separate empty storage namespace and business deduplication; see the migration contract.


IdempotencyStatus ​

ts
type IdempotencyStatus = "PROCESSING" | "COMPLETED";

Defined in: src/interfaces/idempotency-record.interface.ts:9

Lifecycle state of an idempotency record.

  • PROCESSING: a request with this key is currently being handled. A duplicate request arriving in this state should receive HTTP 409 Conflict.
  • COMPLETED: the request finished and its response is cached. A duplicate request with the same fingerprint should be replayed from the stored response.

IdempotencyStorageOperation ​

ts
type IdempotencyStorageOperation = "get" | "create" | "race_get" | "complete" | "delete";

Defined in: src/interfaces/idempotency-options.interface.ts:70

The failed storage call; race_get is the re-read after losing create().


MutateResult ​

ts
type MutateResult = "ok" | "stale";

Defined in: src/interfaces/idempotency-storage.interface.ts:49

Return shape of IdempotencyStorage.complete and IdempotencyStorage.delete.

  • 'ok': a live PROCESSING record completed, or delete removed the owned record / found it logically absent (including expiry).
  • 'stale': complete found a missing, expired, already COMPLETED, or differently owned record; or delete found a live record with another token. No response, TTL, token or createdAt is changed on this path. Expiry alone is sufficient: a replacement does not need to exist.

ReplayHeadersOption ​

ts
type ReplayHeadersOption = boolean | string[];

Defined in: src/interfaces/idempotency-options.interface.ts:32

Variables ​

DEFAULT_HEADER_NAME ​

ts
const DEFAULT_HEADER_NAME: "Idempotency-Key" = 'Idempotency-Key';

Defined in: src/idempotency.constants.ts:29

Default HTTP header name carrying the idempotency key. Matches the IETF draft httpapi-idempotency-key-header-07.


DEFAULT_TTL_SECONDS ​

ts
const DEFAULT_TTL_SECONDS: 86400 = 86_400;

Defined in: src/idempotency.constants.ts:34

Default time-to-live for idempotency records, in seconds (24 hours).


IDEMPOTENCY_OPTIONS ​

ts
const IDEMPOTENCY_OPTIONS: typeof IDEMPOTENCY_OPTIONS;

Defined in: src/idempotency.constants.ts:4

Injection token for the resolved IdempotencyOptions instance.


IDEMPOTENCY_STORAGE ​

ts
const IDEMPOTENCY_STORAGE: typeof IDEMPOTENCY_STORAGE;

Defined in: src/idempotency.constants.ts:9

Injection token for the IdempotencyStorage instance the interceptor uses.


IDEMPOTENCY_SWEEP_OPTIONS ​

ts
const IDEMPOTENCY_SWEEP_OPTIONS: typeof IDEMPOTENCY_SWEEP_OPTIONS;

Defined in: src/idempotency.constants.ts:15

Injection token for SweepOptions. Optional — when not provided the PostgresSweepService runs in disabled mode (no scheduled cleanup).


IDEMPOTENT_METADATA_KEY ​

ts
const IDEMPOTENT_METADATA_KEY: "nestarc:idempotent" = 'nestarc:idempotent';

Defined in: src/idempotency.constants.ts:23

Reflector metadata key carrying the per-handler IdempotentMetadata.

Stored as a plain string (not Symbol) for maximum compatibility with Nest's Reflector.get and Reflect.getMetadata.

Functions ​

Idempotent() ​

ts
function Idempotent(options?): MethodDecorator;

Defined in: src/idempotency.decorator.ts:29

Marks a NestJS controller handler as idempotent.

The IdempotencyInterceptor reads this metadata to decide whether to apply duplicate-request protection: extracting the Idempotency-Key header, computing a request fingerprint, and replaying cached responses for repeats.

Parameters ​

ParameterType
options?IdempotentOptions

Returns ​

MethodDecorator

Examples ​

Basic usage — header is required, body fingerprinted, default TTL.

ts
@Post()
@Idempotent()
createPayment(@Body() dto: CreatePaymentDto) { ... }

Per-handler overrides.

ts
@Post('refunds')
@Idempotent({ ttl: 3600, fingerprint: false })
createRefund(@Body() dto: CreateRefundDto) { ... }

Documentation site: MIT License. Check each package for its license.