# How to add an Idempotency-Key header to every POST from a client

> Give each logical write one Idempotency-Key that every retry reuses, from an SDK feature, an interceptor, or a wrapper, and count the records the server stores.

Source: https://voxgig.com/howto/add-idempotency-key-to-every-post-request

- Audience: api-consumer
- Level: beginner
- Languages: typescript
- Verified: 2026-11-19
- Published: 2026-11-19

## Short answer

Send one `Idempotency-Key` for each logical write and reuse it on every retry. In an SDK generated by sdkgen, pass `feature: { idempotency: { active: true } }` to the constructor: the key is set once for each operation, before the retry feature repeats the request. With Hey API, add a request interceptor and let the HTTP client do the retrying. Fern generates the key from one setting. Without a generator, mint the key before your retry loop.

---
## You will need

Node 22 or later, and an API that honors the `Idempotency-Key` header. The header is defined by an
[IETF draft](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) and not
by an RFC, so each API's own documentation says whether it is supported.[^1] The API here is
`api.json`, an Orders API whose POST declares the header as an optional parameter. The sdkgen
packages ask for Node 24 in `engines`, and npm installed them on Node 22 after `EBADENGINE` warnings. A stand-in
server on 127.0.0.1 stores each order and can then answer 503, which is the failure a key is for.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Fern idempotency key generation](https://buildwithfern.com/learn/sdks/current/deep-dives/idempotency) | You generate SDKs with Fern and want a UUID on every POST and PUT from one setting | An account, a guest session, or Docker to generate, and no statement that a retry reuses the key | You want generation with no account and no container |
| [fetch wrapper](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch) | Any API, no generator, and a retry loop you already own | Every call site has to go through it, and one direct `fetch` is a write with no key | A generated SDK already sits between your code and the API |
| [Hey API request interceptor](https://heyapi.dev/docs/openapi/typescript/clients/ky) | A Hey API client, where one function can key every POST | No key of its own, and one key for each attempt when your own loop retries | You want the generator to own the rule |
| [sdkgen idempotency feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | An SDK generated by sdkgen, in any of its languages, beside its retry feature | Its list of methods that count as writes, and a default key built from `Math.random` | Your client is hand-written, or each key must be a UUID with nothing to configure |
| [stripe-node `idempotencyKey` request option](https://docs.stripe.com/api/idempotent_requests) | You call Stripe, whose client already keys every POST it sends | One vendor's API only, so the rest of your calls still need another row | Your writes go to more than one API |

Voxgig maintains sdkgen. It is one of five options here, not the recommendation.

The rows differ in who owns the rule. A wrapper or an interceptor is your code, so you can read
where the key is minted, and you can also get that wrong. The sdkgen feature and Fern's setting
put the rule in generated code, where it holds for every caller and also keys methods you might
have left alone. stripe-node does the same for one API.

## Turn the feature on and count what the server stores

`generate.sh` scaffolds an sdkgen project from `api.json` with two features and generates the
TypeScript SDK.

```bash title="generate.sh"
npx --yes @voxgig/create-sdkgen@0.31.9 orders --def api.json --target ts --feature idempotency --feature retry
cd orders-sdk/.sdk
npm run generate
```

The generated SDK carries both features and leaves each one off until the constructor passes
`active: true`. `keys.mjs` places two orders through one client. The server stores each order and
answers 503 to the first two attempts at it.

```js title="keys.mjs"
// One client for both orders, built with the feature options of the row.
const connect = (feature) => (base) => {
  const client = new OrdersSDK({ base, feature })
  return (order) => client.Order().create(order)
}
```

```bash
node keys.mjs
```

```text output
two orders, each answered 503 twice before its 201
  feature                                        POSTs  keys  orders stored
  retry                                          6      0     6
  retry, idempotency                             6      2     2
  retry, idempotency with keygen: randomUUID     6      2     2
```

With retry alone the client reports two successes and the server holds six orders. With the
feature on, each order keeps one key across its three attempts, and two orders are stored.

## Read which requests the feature keys

The second half of the same output follows one order through the server, then one read.

```bash
node keys.mjs
```

```text output
retry, idempotency: what the server saw, and one list call after it
  POST /v1/orders  key A   503
  POST /v1/orders  key A   503
  POST /v1/orders  key A   201
  GET  /v1/orders  no key  200
  key A is 24 characters, and the feature issued 1

a create with idempotency_key: 'order-7f3a' arrived with order-7f3a, and the feature issued 0
```

The feature sets the key in the `PreRequest` hook, once for each operation, and the retry feature
then repeats the finished request. A read gets no key. The generated source says which requests
count as writes.

```js title="generated/feature/idempotency/IdempotencyFeature.js"
    _mutating(ctx) {
        const methods = this._options.methods || ['POST', 'PUT', 'PATCH', 'DELETE'];
        const method = ((ctx.spec && ctx.spec.method) || '').toUpperCase();
        if (method && methods.indexOf(method) >= 0) {
            return true;
        }
        const opname = ctx.op && ctx.op.name;
        const ops = this._options.ops || ['create', 'update', 'remove'];
        return ops.indexOf(opname) >= 0;
    }
```

Both lists are options, so the rule is a setting: `methods: ['POST']` with `ops: ['create']`
narrows it to POST requests and the create operation. A caller's own key goes in as `idempotency_key`, the name the
model gives the document's header parameter, and the feature leaves it alone. The generated
TypeScript types omit that argument in the version run here. The default key is four
`Math.random` draws written in hex and padded to 24 characters, and `keygen: randomUUID` swaps in
[a version 4 UUID](https://nodejs.org/api/crypto.html#cryptorandomuuidoptions).[^2]

## Add the key in a Hey API interceptor

Hey API has no idempotency option, and two things it generates are enough. The document's header
parameter becomes a typed `headers` field on `createOrder`. Every client also takes
[request interceptors](https://heyapi.dev/docs/openapi/typescript/clients/ky), and one of them
can key every POST.

```js title="heyapi.mjs"
/** A request interceptor: every POST that has no key yet gets one. */
export const addKey = (request) => {
  if (request.method === 'POST' && !request.headers.has('Idempotency-Key')) {
    request.headers.set('Idempotency-Key', randomUUID())
  }
  return request
}
```

```bash
node heyapi.mjs
```

```text output
the same two orders through the Hey API client
  where the key is minted                        POSTs  keys  orders stored
  no key, ky retries the POST                    6      0     6
  interceptor, ky retries the POST               6      2     2
  interceptor, your loop retries                 6      6     6
  key minted before your loop, sent in headers   6      2     2
```

An interceptor runs once for each call of a generated function. When the `ky` client retries
inside that call, the key is minted once and repeated, as in the second row. When your own loop
calls the function three times, the interceptor mints three keys and the server stores three
orders. The last row mints the key before the loop and passes it in `headers`. The second row
needed two settings as well: [`ky` retries](https://github.com/sindresorhus/ky#retry) a POST only
when `retry.methods` names it, and the generated client lets `ky` retry a status only with
`throwOnError: true`.

## Switch on key generation in Fern

Fern documents two layers, in its `sdk-config.yml` format. Declaring `x-fern-idempotency-headers`
at the root of the document and marking an endpoint `x-fern-idempotent: true` gives callers an
`idempotencyKey` request option. Setting `client.idempotencyKeyGeneration.enabled: true` makes
the SDK [attach a UUIDv4](https://buildwithfern.com/learn/sdks/current/deep-dives/idempotency) to
POST and PUT requests unless the caller supplies a key, and `headerName` and `methods` change
both defaults.

That page describes the key as generated for each request. It does not say whether the SDK's own
retry reuses it, and Fern was not run for this page. Count the keys against your own server
before you rely on it.

## Check it worked

The test asks the server what arrived, because the client saw one success either way.

```js title="keys.test.mjs"
  const order = await client.Order().create(KETTLE)

  const keys = server.state.requests.map((r) => r.key)
  assert.equal(keys.length, 3, 'three attempts reached the server')
  assert.equal(new Set(keys).size, 1, 'one key across all three')
  assert.match(keys[0], /^[0-9a-f]{24}$/, 'the default key is 24 hex characters')
  assert.equal(server.state.orders.length, 1, 'one order stored')
```

```bash
node --test keys.test.mjs
```

```text output
1..14
# tests 14
# suites 0
# pass 14
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

`# pass 14` covers the stand-in, the SDK, the wrapper, and the Hey API client. A second test
places another order and expects a different key.

## When it goes wrong

Every request carries a key, but the server still stores three orders for one call. The key is
minted inside the retry loop, so each attempt arrives as a new order. `pitfall.mjs` runs
`wrapper.mjs`, a loop around `fetch`, beside a copy with that one line moved.

```bash
node pitfall.mjs
```

```text output
two orders through a hand-written loop around fetch
  where the key is minted                        POSTs  keys  orders stored
  before the loop                                6      2     2
  inside the loop                                6      6     6
```

Mint the key where the logical write starts, and pass it down.

The server answers 422 to a write that looks new. The key was reused with a different body, which
the draft tells a server to refuse. A key belongs to one write, so mint it for that order and
never reuse one held by the user or the session.

A job queue reruns a whole task after a crash, and the SDK mints a fresh key for the same order.
Pass a key built from the job's own id as `idempotency_key`.

## When not to do this

Do not adopt sdkgen to send one header. When the client is a few `fetch` calls, the wrapper here
is the smaller change, and you can read every line of it.

Do not keep sdkgen's default key where a key must be a UUID or hard to guess. Pass `keygen`.
Fern's setting generates a UUIDv4 with nothing to pass, and Hey API leaves the generator to you,
which is the better position when keys come from your own records.[^3]

Do not key every method because the sdkgen feature's defaults do. They add the header to PUT,
PATCH, and DELETE, and Stripe's documentation says a key on GET or DELETE has no effect there.
Narrow `methods` and `ops` to what your API documents.

Do not count on a key after its window. Stripe documents that its v1 API can remove keys once
they are 24 hours old, so a retry after that window is a second order.

## Related how-tos

- [Make queue consumer writes safe under redelivery](/howto/queue-consumer-writes-under-at-least-once)

- [Retry fetch calls with exponential backoff in Node.js](/howto/retry-fetch-with-backoff-in-node)

- [Audit SDK retry and timeout defaults before adoption](/howto/audit-sdk-retry-and-timeout-defaults)

- [Generate your first SDK with sdkgen](/howto/first-sdk-with-sdkgen)

- [Make PUT and DELETE safe to retry without a key](/howto/retry-put-and-delete-safely-without-a-key)

## Last verified

Verified 2026-11-19 against Node 22.23.5, `@voxgig/create-sdkgen` 0.31.9, `@voxgig/sdkgen` 4.44.3,
`@hey-api/openapi-ts` 0.99.0, and `ky` 1.14.3. Every output block is what the command preceding it
printed. sdkgen and Hey API each ran on `api.json`, and their output is committed as compiled
JavaScript. Fern was not run. Its options come from its documentation. stripe-node was not run
either; its row comes from Stripe's documentation and the client's source.

[^1]: The draft is at its eighth revision, dated October 22, 2026, six months after the seventh
expired. [Revision 08](https://www.ietf.org/archive/id/draft-ietf-httpapi-idempotency-key-header-08.txt)
adds a third author. It keeps a section of implementations that the RFC Editor is asked to remove
before publication. Stripe's entry opens that list and calls Idempotency-Key a custom HTTP header,
which is the name the draft sets out to standardize.

[^2]: The draft says the value must be a String as
[RFC 9651](https://www.rfc-editor.org/rfc/rfc9651.html#section-3.3.3) defines one, which travels
in double quotes, and its example has them. Stripe's documentation shows the header with a bare
value, and every client run for this page sends one bare. The stand-in reads the value as it comes.

[^3]: stripe-node adds a key of its own to every POST, and its
[source](https://github.com/stripe/stripe-node/blob/master/src/RequestSender.ts) is frank about
the generator. A comment says the client's UUID function has to be cryptographically secure, but
that an idempotency key only has to be unique, and the code falls back to `Math.random` when that
function fails. sdkgen's default uses `Math.random` from the first key, the generator stripe-node
keeps for that failure.