@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
new IdempotencyInterceptor(
reflector,
storage,
moduleOptions): IdempotencyInterceptor;Defined in: src/idempotency.interceptor.ts:120
Parameters
| Parameter | Type |
|---|---|
reflector | Reflector |
storage | IdempotencyStorage |
moduleOptions | IdempotencyOptions |
Returns
Methods
intercept()
intercept(context, next): Observable<unknown>;Defined in: src/idempotency.interceptor.ts:136
Method to implement a custom interceptor.
Parameters
| Parameter | Type | Description |
|---|---|---|
context | ExecutionContext | an ExecutionContext object providing methods to access the route handler and class about to be invoked. |
next | CallHandler | a reference to the CallHandler, which provides access to an Observable representing the response stream from the route handler. |
Returns
Observable<unknown>
Implementation of
NestInterceptor.interceptIdempotencyModule
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:
- App-global:
providers: [{ provide: APP_INTERCEPTOR, useClass: IdempotencyInterceptor }] - Controller-scoped:
@UseInterceptors(IdempotencyInterceptor)on the class - 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
new IdempotencyModule(): IdempotencyModule;Returns
Methods
forRoot()
static forRoot(options): DynamicModule;Defined in: src/idempotency.module.ts:36
Parameters
| Parameter | Type |
|---|---|
options | IdempotencyOptions |
Returns
DynamicModule
forRootAsync()
static forRootAsync(options): DynamicModule;Defined in: src/idempotency.module.ts:58
Parameters
| Parameter | Type |
|---|---|
options | IdempotencyAsyncOptions |
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
IdempotencyStorageOnModuleDestroy
Constructors
Constructor
new MemoryStorage(): MemoryStorage;Returns
Methods
complete()
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
| Parameter | Type | Description |
|---|---|---|
key | string | - |
token | string | - |
response | CompleteResponse | - |
ttlSeconds | number | completed 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
create()
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
| Parameter | Type | Description |
|---|---|---|
key | string | the idempotency key from the client header (already scoped by the interceptor to include endpoint identity) |
fingerprint | string | undefined | SHA-256 of the request body, or undefined if fingerprinting is off |
ttlSeconds | number | lifetime 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
delete()
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
| Parameter | Type |
|---|---|
key | string |
token | string |
Returns
Promise<MutateResult>
Implementation of
get()
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
| Parameter | Type |
|---|---|
key | string |
Returns
Promise<IdempotencyRecord | null>
Implementation of
onModuleDestroy()
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
OnModuleDestroy.onModuleDestroyInterfaces
CompleteResponse
Defined in: src/interfaces/idempotency-storage.interface.ts:6
The response payload captured by the interceptor and persisted by storage.
Properties
body?
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?
optional headers?: Record<string, string>;Defined in: src/interfaces/idempotency-storage.interface.ts:19
Lowercase HTTP response headers captured for replay.
statusCode
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
acquired: boolean;Defined in: src/interfaces/idempotency-storage.interface.ts:34
token?
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?
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
Pick.importsinject?
optional inject?: any[];Defined in: src/interfaces/idempotency-options.interface.ts:221
isGlobal?
optional isGlobal?: boolean;Defined in: src/interfaces/idempotency-options.interface.ts:222
useClass?
optional useClass?: Type<IdempotencyOptionsFactory>;Defined in: src/interfaces/idempotency-options.interface.ts:217
useExisting?
optional useExisting?: Type<IdempotencyOptionsFactory>;Defined in: src/interfaces/idempotency-options.interface.ts:216
useFactory?
optional useFactory?: (...args) =>
| IdempotencyOptions
| Promise<IdempotencyOptions>;Defined in: src/interfaces/idempotency-options.interface.ts:218
Parameters
| Parameter | Type |
|---|---|
...args | any[] |
Returns
| IdempotencyOptions | Promise<IdempotencyOptions>
IdempotencyEvent
Defined in: src/interfaces/idempotency-options.interface.ts:82
Properties
error?
optional error?: IdempotencyEventError;Defined in: src/interfaces/idempotency-options.interface.ts:89
keyHash
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
namespace: string;Defined in: src/interfaces/idempotency-options.interface.ts:87
S3 v1 identity + endpoint namespace hash, independent of the raw key.
outcome
outcome: IdempotencyOutcome;Defined in: src/interfaces/idempotency-options.interface.ts:83
statusCode?
optional statusCode?: number;Defined in: src/interfaces/idempotency-options.interface.ts:88
IdempotencyFingerprintInput
Defined in: src/interfaces/idempotency-options.interface.ts:43
Properties
body
body: unknown;Defined in: src/interfaces/idempotency-options.interface.ts:47
context
context: ExecutionContext;Defined in: src/interfaces/idempotency-options.interface.ts:44
defaultFingerprint
defaultFingerprint: () => string | undefined;Defined in: src/interfaces/idempotency-options.interface.ts:48
Returns
string | undefined
key
key: string;Defined in: src/interfaces/idempotency-options.interface.ts:45
scope
scope: string;Defined in: src/interfaces/idempotency-options.interface.ts:46
IdempotencyObservabilityOptions
Defined in: src/interfaces/idempotency-options.interface.ts:92
Properties
exposeStatusHeaders?
optional exposeStatusHeaders?: boolean;Defined in: src/interfaces/idempotency-options.interface.ts:96
Defaults to true. These headers are generated afresh, never replayed.
onEvent?
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
| Parameter | Type |
|---|---|
event | IdempotencyEvent |
Returns
void | Promise<void>
IdempotencyOptions
Defined in: src/interfaces/idempotency-options.interface.ts:102
Module-level configuration passed to IdempotencyModule.forRoot.
Properties
fingerprint?
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
trueheaderName?
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
'Idempotency-Key'isGlobal?
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
truekeyResolver?
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?
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
255observability?
optional observability?: IdempotencyObservabilityOptions;Defined in: src/interfaces/idempotency-options.interface.ts:191
Optional operational hooks and client-visible status headers.
processingTtl?
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?
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
truescope?
optional scope?: IdempotencyScope;Defined in: src/interfaces/idempotency-options.interface.ts:174
How storage keys are namespaced. See IdempotencyScope.
Default
'endpoint'storage
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?
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
86400 (24 hours)IdempotencyOptionsFactory
Defined in: src/interfaces/idempotency-options.interface.ts:205
Factory contract for useClass / useExisting async registration paths.
Methods
createIdempotencyOptions()
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
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
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?
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
key: string;Defined in: src/interfaces/idempotency-record.interface.ts:16
The exact value of the Idempotency-Key header from the original request.
responseBody?
optional responseBody?: string;Defined in: src/interfaces/idempotency-record.interface.ts:40
Opaque versioned replay payload; storage must preserve it unchanged.
responseHeaders?
optional responseHeaders?: Record<string, string>;Defined in: src/interfaces/idempotency-record.interface.ts:43
Lowercase HTTP response headers captured for replay.
status
status: IdempotencyStatus;Defined in: src/interfaces/idempotency-record.interface.ts:34
Current lifecycle state.
statusCode?
optional statusCode?: number;Defined in: src/interfaces/idempotency-record.interface.ts:37
Captured HTTP status code of the original handler response.
token
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:
- Atomic creation (
NXsemantics) — two concurrentcreate()calls for the same key must result in exactly oneacquired: trueand oneacquired: false. - 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 owncreate()call. This prevents the TTL-eviction race where a slow caller would otherwise clobber a newer caller's record. createdAtimmutability —complete()and any other mutation MUST preserve thecreatedAtfield of the original PROCESSING record. See IdempotencyRecord.createdAt.- 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().
- 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.
- 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()
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
| Parameter | Type | Description |
|---|---|---|
key | string | - |
token | string | - |
response | CompleteResponse | - |
ttlSeconds | number | completed 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()
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
| Parameter | Type | Description |
|---|---|---|
key | string | the idempotency key from the client header (already scoped by the interceptor to include endpoint identity) |
fingerprint | string | undefined | SHA-256 of the request body, or undefined if fingerprinting is off |
ttlSeconds | number | lifetime 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()
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
| Parameter | Type |
|---|---|
key | string |
token | string |
Returns
Promise<MutateResult>
get()
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
| Parameter | Type |
|---|---|
key | string |
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
enabled: true;Defined in: src/interfaces/idempotency-options.interface.ts:272
fingerprint?
optional fingerprint?:
| boolean
| IdempotencyFingerprintResolver;Defined in: src/interfaces/idempotency-options.interface.ts:263
Override the module-level fingerprint setting for this handler.
Inherited from
keyResolver?
optional keyResolver?: IdempotencyKeyResolver;Defined in: src/interfaces/idempotency-options.interface.ts:253
Override the module-level key resolver for this handler.
Inherited from
maxKeyLength?
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?
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?
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
trueInherited from
ttl?
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
Defined in: src/interfaces/idempotency-options.interface.ts:228
Per-handler overrides accepted by the Idempotent decorator.
Extended by
Properties
fingerprint?
optional fingerprint?:
| boolean
| IdempotencyFingerprintResolver;Defined in: src/interfaces/idempotency-options.interface.ts:263
Override the module-level fingerprint setting for this handler.
keyResolver?
optional keyResolver?: IdempotencyKeyResolver;Defined in: src/interfaces/idempotency-options.interface.ts:253
Override the module-level key resolver for this handler.
maxKeyLength?
optional maxKeyLength?: number;Defined in: src/interfaces/idempotency-options.interface.ts:258
Override the module-level maximum key length for this handler.
processingTtl?
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?
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
truettl?
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
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
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
| Parameter | Type |
|---|---|
input | IdempotencyFingerprintInput |
Returns
string | undefined | Promise<string | undefined>
IdempotencyKeyResolver
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
| Parameter | Type |
|---|---|
context | ExecutionContext |
Returns
string | undefined | Promise<string | undefined>
IdempotencyOutcome
type IdempotencyOutcome =
| "created"
| "replayed"
| "conflict"
| "mismatch"
| "bypassed"
| "stale"
| "complete_error"
| "storage_error";Defined in: src/interfaces/idempotency-options.interface.ts:59
IdempotencyScope
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 SAMEIdempotency-Keyvalue 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
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
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
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
type ReplayHeadersOption = boolean | string[];Defined in: src/interfaces/idempotency-options.interface.ts:32
Variables
DEFAULT_HEADER_NAME
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
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
const IDEMPOTENCY_OPTIONS: typeof IDEMPOTENCY_OPTIONS;Defined in: src/idempotency.constants.ts:4
Injection token for the resolved IdempotencyOptions instance.
IDEMPOTENCY_STORAGE
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
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
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()
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
| Parameter | Type |
|---|---|
options? | IdempotentOptions |
Returns
MethodDecorator
Examples
Basic usage — header is required, body fingerprinted, default TTL.
@Post()
@Idempotent()
createPayment(@Body() dto: CreatePaymentDto) { ... }Per-handler overrides.
@Post('refunds')
@Idempotent({ ttl: 3600, fingerprint: false })
createRefund(@Body() dto: CreateRefundDto) { ... }