---
url: >-
  https://game-engine-io.github.io/enginex-frontend-sdk/concepts/extensibility.md
---
# Extensibility

Two extension points to integrate the SDK with your app's runtime: per-call `fetchOptions` and
client `hooks`. For those who write SDK product packages, there is also the
[extension contract](#product-packages).

## `fetchOptions`: per-call `fetch` options

Every method accepts `options.fetchOptions`, merged into the `fetch` of **every** attempt of the
request (the initial one and the retry after a renewed 401). Use it for runtime-specific features, such as
Next.js's data cache:

```ts
const config = await enginex.config.get(undefined, {
  fetchOptions: { next: { revalidate: 60, tags: ['config'] } },
})
```

You can also adjust `cache`, `credentials` and other standard `RequestInit` options:

```ts
await enginex.config.getBranding(undefined, { fetchOptions: { cache: 'no-store' } })
```

`method`, `body` and `signal` are always the SDK's: even if given in `fetchOptions`, they are
ignored — use `options.signal` for cancellation. In `headers`, the names the SDK controls
(`authorization`, `x-original-host`, `idempotency-key`, `content-type`, `accept`,
`accept-language`) are always removed and replaced by the SDK's — even when this particular
request does not set one of them (e.g. an `Authorization` does not survive a retry without a token, in `optional`
mode) — comparing names case-insensitively, and applying to all three
forms of `HeadersInit` (object, `Headers`, array of pairs). Any other extra header passes
through normally:

```ts
await enginex.config.get(undefined, {
  fetchOptions: { headers: { 'x-my-trace-id': traceId } }, // reaches the gateway
})
```

## `hooks`: client observability

`createEnginexClient({ hooks })` calls `onRequest`/`onResponse` on each attempt and `onError` once
per call that fails, for logging, metrics or tracing:

```ts
const enginex = createEnginexClient({
  hooks: {
    onRequest(ctx) {
      span.addEvent('request', ctx)
    },
    onResponse(ctx) {
      metrics.timing('enginex.request', ctx.durationMs, { status: String(ctx.status) })
    },
    onError(error, ctx) {
      logger.warn('enginex request failed', { code: error.code, ...ctx })
    },
  },
})
```

* `onRequest(ctx)` and `onResponse(ctx)` fire on each attempt: the initial one (`attempt: 1`) and, if the
  gateway responds 401 and the session is renewed, the retry (`attempt: 2`). Requests with `auth: 'none'`
  or `'current'` (e.g. `logout`) never have a second `attempt`.
* `onError(error, ctx)` fires **only once per public call that fails** — never per
  attempt — with the final `EnginexError`: the same error the method's `Promise` rejects with. In
  `onError`, `ctx.attempt` can be `0` when the call failed before any network attempt
  (e.g. `CONFIGURATION_ERROR` in resolving `baseUrl`/`tenantHost`/`fetch`).
* **Internal SDK requests never fire any hook**: session renewal
  (`POST /auth/refresh`, triggered by a 401) is completely invisible to `onRequest`,
  `onResponse` and `onError` — only the public request that originated the 401 is reported. Likewise,
  an error that is part of a method's normal flow (e.g. `2FA_REQUIRED` in `login`, which becomes the
  return value `{ status: '2fa_required' }`) or that the method swallows by contract (e.g. `logout`, which
  never rejects) does not fire `onError`.
* `ctx` never includes headers, tokens, body or the query string (which could carry secrets, e.g.
  the token of a password reset link): only `{ method, path, url, attempt }`, and in `onResponse`
  also `status`, `durationMs` and `requestId` (the response's `X-Request-ID`, when present). `url` and
  `path` never carry the query string.
* In multipart requests (e.g. [`kyc.uploadDocument`](/flows/kyc)), `ctx.body` carries only a summary:
  `{ kind: 'form-data', fields: [{ name, type?, size? }] }` — the name of each field (e.g. `file`) and,
  for files, type and size. Never the original file name or content, nor the value of text
  fields. JSON bodies never appear in `ctx`.
* Every hook is called via `safeCall`: a hook that throws affects neither the request nor the other hooks —
  the same isolation as [Session and tokens](/concepts/session) for
  `onSessionChange`/`onSessionExpired`/`onValidationIssue`.

## Product packages {#product-packages}

The product packages (`@getenginex/sdk-igaming`, `@getenginex/sdk-predictions`) are built on top of the
core client through the `@getenginex/sdk/extension` entry. It is a stable public API (versioned and with a
snapshot in CI), but **intended for SDK packages, not for apps**: an app only creates the client and passes it
to the product package.

```ts
import type { CallOptions, EnginexClient } from '@getenginex/sdk'
import { getExtensionTransport, lazy, wire } from '@getenginex/sdk/extension'
import { z } from 'zod/mini'

const gameSchema = /* @__PURE__ */ lazy(() => wire({ game_id: z.string(), name: z.string() }))

export function createIgaming(client: EnginexClient) {
  const transport = getExtensionTransport(client)
  return {
    casino: {
      getGame: ({ gameId }: { gameId: string }, options?: CallOptions) =>
        transport.request({
          method: 'GET',
          path: `/casino/games/${encodeURIComponent(gameId)}`,
          auth: 'optional',
          schema: gameSchema(),
          options,
        }),
    },
  }
}
```

* `getExtensionTransport(client)` returns the **client's own** transport: session, token renewal
  after a 401, tenant, locale, timeout, `hooks`, `validation` and `dispose()` are always those of the
  app's client — a product package never creates its own session, tenant or transport. The
  transport is not exposed on the client object; a value that is not a client created by
  `createEnginexClient` (including a `{ ...client }` copy) throws `CONFIGURATION_ERROR`.
* `request(spec)` and `requestPage(spec)` receive a spec with `method`, `path`, `query`, `body`,
  `auth` (`'none'`, `'optional'` or `'required'`), `idempotent`, `schema`/`item`,
  `page`/`perPage`/`perPageParam`, `validation: 'strict'` and `options` (the `CallOptions` received
  by the public method, passed on as they are). `idempotent: true` sends an `Idempotency-Key`
  generated per call and reused on the retry after a renewed 401. An `auth`, `validation` or
  `perPageParam` outside those values rejects with `CONFIGURATION_ERROR` before any `fetch`; a
  `path` segment that is `.` or `..` (e.g. an id coming from the app) rejects with `INVALID_ARGUMENT`
  (`status: 0`), also before the `fetch`, because the URL would normalize it to another route.
* Identify errors with `isEnginexError(error, code)`, not with `instanceof EnginexError`: in
  CommonJS, the main entry and the extension entry are separate files, each with its own copy of the
  class.
* `reportError(error, ctx)` is for failures the package detects after a successful response:
  it normalizes into `EnginexError`, calls `onError` exactly once and returns the error to throw.
* `wire`, `mapOf` and `lazy` are the same schema helpers as the core (wire in `snake_case`, output in
  `camelCase`, schemas built only on first use so as not to weigh down the bundle of those who do not use them).

### Custom realtime topic {#custom-topic}

A product package that publishes its own topics defines them with `defineTopic` and validates the payload with
`wire` (the same schema helper as HTTP responses). The topic below is illustrative: the gateway has to publish
it for messages to arrive.

```ts
import { defineTopic, lazy, wire } from '@getenginex/sdk/extension'
import { createRealtime } from '@getenginex/sdk/realtime'
import { z } from 'zod/mini'

// The wire payload is snake_case; the handler receives camelCase ({ tournamentId, rank, points }).
const leaderboardSchema = /* @__PURE__ */ lazy(() =>
  wire({ tournament_id: z.string(), rank: z.number(), points: z.number() }),
)

// Public topic: the factory takes the id and builds `tournament:<id>`.
export const tournamentLeaderboard = defineTopic({
  prefix: 'tournament',
  private: false,
  messageType: 'leaderboard_update',
  schema: leaderboardSchema,
})

// Private topic: no id; realtime uses the session's `sub` (`tournament-rewards:<sub>`).
export const myTournamentRewards = defineTopic({
  prefix: 'tournament-rewards',
  private: true,
  messageType: 'reward_granted',
  schema: lazy(() => wire({ tournament_id: z.string(), amount: z.number() })),
})

const realtime = createRealtime(enginex)
const off = realtime.subscribe(tournamentLeaderboard('t-1'), (update, meta) => {
  console.log(update.tournamentId, update.rank, update.points, meta.kind)
})
realtime.onResync(tournamentLeaderboard('t-1'), () => reloadLeaderboard()) // reload the baseline over HTTP
```

* `prefix` is the topic name at the gateway, without the trailing `:`. `private: false` makes the factory
  require the id; `private: true` makes it take none, and `subscribe` throws `UNAUTHENTICATED` without a
  session.
* `messageType` is the type of the topic's data messages on the wire; the others are ignored.
* The message is validated in the client's mode (`strict` discards it, `warn` recovers it field by field and
  reports through `onValidationIssue`) and reaches the handler in `camelCase`. Wrap the schema in `lazy` so it is
  only built on the first subscription.
* `snapshots: 'ignore'` skips the sequenced mode `snapshot`s when they have another format (as in
  `coreTopics.balance()`).
* An invalid definition (empty prefix, prefix outside the gateway format, empty `messageType`, a schema that is
  not Zod) or an invalid id throws `CONFIGURATION_ERROR`.

Export the factories in an entry of their own (as `@getenginex/sdk-predictions/realtime` does), so that an
app that does not use realtime does not load the schemas. The connection, reconnection and `onResync` are the
core's: see [Realtime](/concepts/realtime).

### Custom mutation {#custom-mutation}

Every options object a mutation factory returns (`m.deposits.createPix()`, or one built with
[`queryScope`](/frameworks/#query-scope)) carries its own idempotency attempt: after an ambiguous failure
(`NETWORK_ERROR`, `TIMEOUT`, 5xx, `KEY_IN_USE`, `VALIDATION_ERROR` after a 2xx), a new call with the same input
reuses the `Idempotency-Key`. An adapter that recreates the options on every render must keep the attempt
somewhere that lives longer, as `useEnginexMutation` does per hook instance. `@getenginex/sdk/extension` has
the pieces:

```ts
import { createAttempts, mutationCallOf, runMutation, type Attempts } from '@getenginex/sdk/extension'
import type { EnginexMutationOptions } from '@getenginex/sdk/query'

/** One attempt per component instance, created once (not on every render). */
export function createMutationRunner() {
  const shared = createAttempts()
  return function mutationFnOf<I, R>(options: EnginexMutationOptions<I, R>): (input: I) => Promise<R> {
    // Read the call from the original options: a `{ ...options }` copy does not carry it.
    const call = mutationCallOf<I, R>(options)
    if (call === undefined) return options.mutationFn // not an SDK mutation: keep its own mutationFn
    // The method is part of the fingerprint: switching from deposit to withdrawal never reuses a key.
    const method = options.mutationKey
    const attempts: Attempts = {
      keyFor: (input) => shared.keyFor({ method, input }),
      settle: (input, error) => shared.settle({ method, input }, error),
    }
    return (input) => runMutation(call, attempts, input)
  }
}
```

```ts
import { createMutations } from '@getenginex/sdk/query'

const mutationFnOf = createMutationRunner() // when the component is created
const m = createMutations(enginex)

// On every render: new options, the same attempt.
const createPix = m.deposits.createPix()
const input = { amount: 5000 }
const deposit = await mutationFnOf(createPix)(input) // a retry after NETWORK_ERROR reuses the key
for (const queryKey of createPix.invalidates(input, deposit)) {
  await queryClient.invalidateQueries({ queryKey })
}
```

* `mutationCallOf(options)` returns the SDK call (`call`, `idempotent`, `fixedKey`) or `undefined` for a
  mutation that did not come from a factory. It is a non-enumerable property: read it from the original
  options, never from a copy.
* `createAttempts()` holds at most one open attempt. `keyFor(input)` returns its key when the input has the same
  content (compared with `fingerprint`), or opens a new one; `settle(input, error?)` keeps it only after a
  failure for which `isAmbiguousFailure(error)` is `true`.
* `runMutation(call, attempts, input)` sends the key (or the fixed `idempotencyKey` of the factory), closes the
  attempt with the result and always rejects with an `EnginexError`.

The app-side rule is in [Idempotency](/concepts/idempotency); the React and Vue adapters already do this (see
[Idempotency in mutations](/frameworks/react#idempotency-in-mutations)).
