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.
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:
const config = await enginex.config.get(undefined, {
fetchOptions: { next: { revalidate: 60, tags: ['config'] } },
})You can also adjust cache, credentials and other standard RequestInit options:
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:
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:
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)andonResponse(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 withauth: 'none'or'current'(e.g.logout) never have a secondattempt.onError(error, ctx)fires only once per public call that fails — never per attempt — with the finalEnginexError: the same error the method'sPromiserejects with. InonError,ctx.attemptcan be0when the call failed before any network attempt (e.g.CONFIGURATION_ERRORin resolvingbaseUrl/tenantHost/fetch).- Internal SDK requests never fire any hook: session renewal (
POST /auth/refresh, triggered by a 401) is completely invisible toonRequest,onResponseandonError— 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_REQUIREDinlogin, which becomes the return value{ status: '2fa_required' }) or that the method swallows by contract (e.g.logout, which never rejects) does not fireonError. ctxnever 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 inonResponsealsostatus,durationMsandrequestId(the response'sX-Request-ID, when present).urlandpathnever carry the query string.- In multipart requests (e.g.
kyc.uploadDocument),ctx.bodycarries 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 inctx. - 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 foronSessionChange/onSessionExpired/onValidationIssue.
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.
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,validationanddispose()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 bycreateEnginexClient(including a{ ...client }copy) throwsCONFIGURATION_ERROR.request(spec)andrequestPage(spec)receive a spec withmethod,path,query,body,auth('none','optional'or'required'),idempotent,schema/item,page/perPage/perPageParam,validation: 'strict'andoptions(theCallOptionsreceived by the public method, passed on as they are).idempotent: truesends anIdempotency-Keygenerated per call and reused on the retry after a renewed 401. Anauth,validationorperPageParamoutside those values rejects withCONFIGURATION_ERRORbefore anyfetch; apathsegment that is.or..(e.g. an id coming from the app) rejects withINVALID_ARGUMENT(status: 0), also before thefetch, because the URL would normalize it to another route.- Identify errors with
isEnginexError(error, code), not withinstanceof 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 intoEnginexError, callsonErrorexactly once and returns the error to throw.wire,mapOfandlazyare the same schema helpers as the core (wire insnake_case, output incamelCase, schemas built only on first use so as not to weigh down the bundle of those who do not use them).
Custom realtime 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.
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 HTTPprefixis the topic name at the gateway, without the trailing:.private: falsemakes the factory require the id;private: truemakes it take none, andsubscribethrowsUNAUTHENTICATEDwithout a session.messageTypeis the type of the topic's data messages on the wire; the others are ignored.- The message is validated in the client's mode (
strictdiscards it,warnrecovers it field by field and reports throughonValidationIssue) and reaches the handler incamelCase. Wrap the schema inlazyso it is only built on the first subscription. snapshots: 'ignore'skips the sequenced modesnapshots when they have another format (as incoreTopics.balance()).- An invalid definition (empty prefix, prefix outside the gateway format, empty
messageType, a schema that is not Zod) or an invalid id throwsCONFIGURATION_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.
Custom mutation
Every options object a mutation factory returns (m.deposits.createPix(), or one built with queryScope) 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:
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)
}
}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) orundefinedfor 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 withfingerprint), or opens a new one;settle(input, error?)keeps it only after a failure for whichisAmbiguousFailure(error)istrue.runMutation(call, attempts, input)sends the key (or the fixedidempotencyKeyof the factory), closes the attempt with the result and always rejects with anEnginexError.
The app-side rule is in Idempotency; the React and Vue adapters already do this (see Idempotency in mutations).