Idempotency Middleware

Deduplicate replays of mutating requests via idempotency keys

Basic Usage

import { idempotency } from '@cleverbrush/client/idempotency';

const client = createClient(api, {
    middlewares: [
        idempotency(),           // adds X-Idempotency-Key to mutations
        retry({ limit: 3 }),     // preserves the key across retries
    ],
});

// First call — key is generated
await client.todos.create({ body: { title: 'Buy milk' } });

// Retry — same key, server returns stored response

Server Integration

The server-side idempotency() middleware reads the header, stores the response, and replays it for duplicate keys.

import { idempotency } from '@cleverbrush/server';

server.handle(CreateTodo, createHandler, {
    middlewares: [idempotency({ ttl: 86_400_000 })],
});

How It Works

  • On mutation: Client auto-generates a UUID v4 as X-Idempotency-Key header.
  • On server: First request with a key runs the handler and stores the response. Replays return the stored response immediately.
  • On retry: The key is preserved — retried requests are treated as replays, not new operations.

Options (Client)

OptionTypeDefault
headerNamestring"X-Idempotency-Key"
keyGenerator(url, init) => stringuuid v4
condition(url, init) => booleanmutations only

Options (Server)

OptionTypeDefault
ttlnumber86400000 (24h)
headerNamestring"x-idempotency-key"
skip(ctx) => booleannon-mutating requests