Migrating a Next player
This guide takes an existing Next player (such as enginex-frontend-player, -igaming and -predictions) to @getenginex/sdk-next gradually: the SDK comes in alongside the current code, and each screen switches its data when it is ready. Nothing has to change all at once.
The starting point is today's players:
| Piece | Today | File |
|---|---|---|
| Next | ^16.3, App Router, src/proxy.ts | package.json |
| React and TanStack | React ^19.2, @tanstack/react-query ^5.101 | package.json |
| Tokens | zustand persist in localStorage (key auth-storage); the server never sees the token | src/shared-modules/auth/ui/stores/useAuthStore.ts |
QueryClient | singleton in the browser (staleTime 5 min, retry 1, no refetch on focus); user keys cleared by a manual list on logout | src/app/(server-pages)/ClientProviders.tsx |
| SSR | anonymous and per tenant; prefetch with new QueryClient() → prefetchQuery → dehydrate → <HydrationBoundary> | src/app/(server-pages)/(igaming)/layout.tsx, src/subapps/igaming/ui/pages/lobby-prefetch.server.ts |
| Tenant on the server | host with a fallback to x-forwarded-host | the same layouts |
| Gateway | NEXT_PUBLIC_API_URL; /api/:path* and /dev/:path* rewrites | next.config.ts |
x-original-host | proxy.ts writes the header only on /api and /dev | src/proxy.ts |
| Balance | 10 s polling in React Query and a store fed by its own WebSocket (wsService) | src/shared-modules/wallet/ui/hooks/useBalanceSync.ts, src/shared-modules/realtime/ |
1. Install
pnpm add @getenginex/sdk @getenginex/sdk-next
pnpm add @getenginex/sdk-igaming # casino/sportsbook player
pnpm add @getenginex/sdk-predictions # predictions playerThe player's @tanstack/react-query, react and next already work (peers ^5, >=19 and >=15).
2. Gateway: NEXT_PUBLIC_API_URL → ENGINEX_GATEWAY_URL
The server client reads the gateway URL from ENGINEX_GATEWAY_URL (server-only, read on every request). Set it to the same value as NEXT_PUBLIC_API_URL in every environment (.env.local, the deploy, Amplify/Kubernetes):
NEXT_PUBLIC_API_URL=https://gateway.operador.com # stays: rewrites and the current code
ENGINEX_GATEWAY_URL=https://gateway.operador.com # new: getEnginexServerAlternative without a new variable: getEnginexServer({ baseUrl: process.env.NEXT_PUBLIC_API_URL }). Remember that NEXT_PUBLIC_* is inlined at build time; ENGINEX_GATEWAY_URL is read at runtime.
baseUrl is only the origin
The SDK accepts '' (same origin) or the gateway's origin (https://host[:port]) and appends /api/v1 on its own. A value with a path (https://gateway.operador.com/api), a trailing slash, a query or credentials throws CONFIGURATION_ERROR when the client is created. If the player's NEXT_PUBLIC_API_URL carries /api, drop it from the value of ENGINEX_GATEWAY_URL.
3. Rewrites and proxy.ts: leave them as they are
The players' next.config.ts already rewrites /api and /dev to the gateway before the locale rewrites (an order that matters), and src/proxy.ts already writes x-original-host on those routes. That is all the browser client needs: it calls /api/v1/... on the same origin.
withEnginexis optional. It adds the gateway rewrite after the app's; since the player already has/api/:path*and/dev/:path*with no condition, the helper would add nothing. Only switch if you want to drop the manual rewrite, and check the order against the locale rewrites.- Tenant on the server:
getEnginexServeruseshost→x-forwarded-host, the same order the layouts use today (headersList.get('host') || headersList.get('x-forwarded-host')). It does not needtrustOriginalHost.
Ingress that rewrites the Host
If in some environment the ingress rewrites the Host to an internal name (e.g. the Service name), getEnginexServer would take that name as the tenant. In that case, pick one of the two:
resolveHost, reading the header where the ingress stores the public domain (see Tenant); ortrustOriginalHost: truewith aproxy.tsthat overwritesx-original-hoston every request that renders, not just on/apiand/dev:
// src/proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const headers = new Headers(request.headers)
// The public domain comes from the header where the ingress stores it, since `Host` arrives rewritten. Here,
// `x-forwarded-host`: swap in your ingress's header (check in production which one it is).
const host =
request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')
// Always overwrite (or delete): the value the browser sent never reaches SSR or the gateway.
if (host) headers.set('x-original-host', host)
else headers.delete('x-original-host')
return NextResponse.next({ request: { headers } })
}
export const config = {
// Every request that renders (pages, /api, /dev), except Next's static files.
matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}Without this proxy.ts, do not turn on trustOriginalHost: on a page, x-original-host comes from the browser, and anyone could choose the SSR operator. Today's proxy.ts has a shortcut that does not clone the headers when the browser already sends x-original-host equal to host; that is still correct, but the current matcher (/api, /dev) does not cover pages.
4. Tokens: a TokenStore on top of zustand
The SDK does not need another place for the session: a TokenStore over useAuthStore makes the SDK read and write the same tokens as the rest of the player, in the same auth-storage in localStorage.
// src/shared/lib/enginex.ts
import { createEnginexClient, type TokenStore } from '@getenginex/sdk'
import { createIgaming } from '@getenginex/sdk-igaming'
import { useAuthStore } from '@/shared-modules/auth/ui/stores/useAuthStore'
const authStoreTokens: TokenStore = {
get() {
const { accessToken, refreshToken } = useAuthStore.getState()
return accessToken && refreshToken ? { accessToken, refreshToken } : null
},
set({ accessToken, refreshToken }) {
useAuthStore.getState().updateTokens(accessToken, refreshToken)
useAuthStore.setState({ isAuthenticated: true })
},
clear() {
useAuthStore.getState().logout()
},
subscribe(listener) {
return useAuthStore.subscribe((state, prev) => {
if (state.accessToken !== prev.accessToken || state.refreshToken !== prev.refreshToken) listener()
})
},
}
export const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: authStoreTokens })
export const igaming = createIgaming(enginex)- The player's login and logout keep working: the store's
setAuth/logoutchange the tokens andsubscribenotifies the SDK. In phase A (below) login and logout belong only to the player; in phase B, a login done by the SDK (enginex.auth.login) writes the tokens viaset, and the store'suserremains the player's. - On the server this module has no tokens (
persistfinds nolocalStorage), so importing it in a Client Component rendered during SSR is safe. For data on the server, always usegetEnginexServer. - Exactly one refresh owner: see the section below before turning the client on in production.
- The cookie is optional: the session can stay in
localStorage. Moving tonextCookieTokenStoreonly makes sense for SSR with player data, and brings the costs from the comparison table (HTTPS required outsidelocalhost, refresh token in the logs, care with cache and HTML).
A single refresh owner
With both clients reading the same store, both know how to renew the session: the SDK renews before the access token expires (2 minutes before) and after a 401; the player's HTTP client (http-client.api.browser.ts) renews after a 401. The SDK usually gets there first, but nothing guarantees it (background tabs, clock, a 401 from both at the same time). If both exchange the same refresh token, the second refresh may be refused and the session drops. That is why the migration has one refresh owner at a time:
Phase A, coexistence: the player refreshes, the SDK does not. The SDK client boots with sessionOwner: 'app': it uses the access token in the store, never calls /auth/refresh and neither writes nor clears tokens (auth.login and auth.logout throw CONFIGURATION_ERROR before sending). The current client remains the refresh owner and writes the new tokens to useAuthStore, and the TokenStore's subscribe notifies the SDK. When the gateway refuses the token (401), the SDK calls onAccessTokenRejected once per token, even in a burst of queries; that is the place to ask the owner for the refresh. See Session and tokens.
// src/shared/lib/enginex.ts (fase A)
export const enginex = createEnginexClient({
locale: 'pt-BR',
tokenStore: authStoreTokens,
sessionOwner: 'app', // the player's HTTP client is the only one that refreshes
// An SDK 401 (expired token) asks its owner for the refresh, which already avoids duplicate refreshes.
onAccessTokenRejected: () => {
if (useAuthStore.getState().refreshToken) void refreshPlayerSession() // e.g. the current client's refreshOnce/sessionProvider.refreshToken()
},
})The cost: an SDK call made between the access token's expiry and the player's next refresh fails with UNAUTHENTICATED (the gateway's 401, with no refresh or retry). useEnginexQuery does not retry this error. Refetch the queries in error when the token changes:
// in a component inside the EnginexProvider (e.g. ClientProviders)
import { enginexKeys } from '@getenginex/sdk/query'
import { useQueryClient } from '@tanstack/react-query'
import { useEffect } from 'react'
const queryClient = useQueryClient()
useEffect(
() =>
useAuthStore.subscribe((state, prev) => {
if (state.accessToken && state.accessToken !== prev.accessToken) {
void queryClient.refetchQueries({
queryKey: enginexKeys.user(),
predicate: (query) => query.state.status === 'error',
})
}
}),
[queryClient],
)A mutation that failed this way is not retried on its own: show the error with "try again", or, in a mutateAsync, wait for the player's refresh and call again once. A 401 releases the idempotency key (it is not an ambiguous failure): the new call is a new operation, and it does not duplicate anything because the gateway refused the first one before processing it.
Phase B, the SDK is the owner. Once login and authenticated calls already go through the SDK, flip it: switch to sessionOwner: 'sdk' (the default; remove the sessionOwner and the onAccessTokenRejected above, which together only apply in phase A), and remove the refresh from the old interceptor (whatever is left of the player's HTTP client only reads the token from the store; a 401 there becomes an error or calls an SDK query). From then on the SDK renews before expiry and after a 401, and writes to the store via set.
Never leave both renewing at the same time, not even for one deploy.
5. Provider with the existing QueryClient
In ClientProviders.tsx, wrap the tree with EnginexProvider, passing the same QueryClient:
// src/app/(server-pages)/ClientProviders.tsx (excerpt)
'use client'
import { EnginexProvider } from '@getenginex/sdk-next'
import { QueryClientProvider } from '@tanstack/react-query'
import { enginex } from '@/shared/lib/enginex'
export default function ClientProviders({ children }: ClientProvidersProps) {
const queryClient = getQueryClient() // the same one as today: staleTime 5 min, retry 1
return (
<EnginexProvider client={enginex} queryClient={queryClient}>
{/* the current QueryClientProvider can go: the EnginexProvider already renders it with the same client */}
{children}
</EnginexProvider>
)
}- The player's
QueryClientis used as-is: the 5-minutestaleTimestill applies to the SDK's queries and avoids the refetch after hydration. The SDK's 60 sstaleTimeonly applies when the app does not pass its own. - On user switch the provider removes
['enginex', 'user']. The player's old keys (['wallet'],['campaignOffers']...) stay in theclearUserScopedQuerieslist until the last screen that uses them is migrated.
6. Switch queries one screen at a time
The SDK's keys (['enginex', 'user', userId, 'wallet', 'getBalance']) differ from the player's (['balance']). Migrate the readers and writers of the same data together: if the balance comes from the SDK but the deposit still invalidates ['balance'], the new balance is not updated after the deposit.
Example, the balance (useBalanceSync.ts):
'use client'
import { useEnginexQueries, useEnginexQuery } from '@getenginex/sdk-next'
export function useBalance() {
const q = useEnginexQueries()
return useEnginexQuery(q.wallet.getBalance(), { refetchInterval: 10_000 })
}And the deposit, which invalidates balance, transactions and deposits on its own:
import { useEnginexMutation, useEnginexMutations } from '@getenginex/sdk-next'
const m = useEnginexMutations()
const pix = useEnginexMutation(m.deposits.createPix())Remove the manual idempotency. The crypto.randomUUID() calls and the key Maps that the player keeps for deposit, withdrawal and bonus go away with it: with useEnginexMutation, the Idempotency-Key is only reused after an ambiguous failure (network, timeout, 5xx, KEY_IN_USE or VALIDATION_ERROR after a 2xx), for the same input, and is kept per hook instance. A "try again" with a literal pix.mutate({ amount }) already reuses the key. Only keep a key of your own (m.deposits.createPix({ idempotencyKey })) where the operation needs to survive a reload. See React.
User keys. To invalidate the SDK's data from inside a component, useUserKey('wallet') (from @getenginex/sdk-next) returns the signed-in player's prefix, or null with no session; outside a component, enginexKeys.user(userId, 'wallet').
An order that works well: configuration and catalog (public, no risk), then balance and wallet (reading and deposit/withdrawal together), then the rest. The player's hooks that already call the gateway keep working in the meantime.
7. Server-side prefetch
Today's prefetchCatalog creates a QueryClient, calls prefetchQuery with its own keys and returns the dehydrate. With the SDK:
// src/app/(server-pages)/(igaming)/layout.tsx (excerpt)
import { HydrationBoundary } from '@tanstack/react-query'
import { createIgaming } from '@getenginex/sdk-igaming'
import { createIgamingQueries } from '@getenginex/sdk-igaming/query'
import { getEnginexServer, prefetchEnginex } from '@getenginex/sdk-next/server'
const enginex = await getEnginexServer({ next: { revalidate: 300, tags: ['catalog'] } })
const catalog = await prefetchEnginex(createIgamingQueries(createIgaming(enginex)), (ig) => [
ig.casino.listCategories(),
ig.casino.listProviders(),
])
return (
<HydrationBoundary state={catalog}>
<IGamingLayout>{children}</IGamingLayout>
</HydrationBoundary>
)- The tenant comes from
headers()insidegetEnginexServer; the layout no longer needs to read thehost. - Switch the component along with it: the rail needs to read with
useEnginexQuery(ig.casino.listCategories()), or the hydrated data (with the SDK's key) goes unused and the component fetches its own. - Tags are fixed per call. The player today uses one tag per host (
catalog-${host}) to invalidate a single tenant; to keep that, read the host yourself and pass it intags. The response is already separated per tenant in the Data Cache key (the request'sX-Original-Hostis part of it). - The prefetch stays anonymous: no player data in SSR, as today.
- Do not list
sdk-nextinserverExternalPackages: outside the server bundle, theserver-onlyimport of the/serverentry fails andnext buildstops with theserver-onlyerror. If the player already has that list, check that the SDK is not in it.
8. Realtime: turn off the player's own WebSocket before useRealtimeSync
useRealtimeSync() opens the SDK's connection and invalidates balance and notifications on every message. With the player's wsService still on for the same events, there are two connections and each balance_update is handled twice (zustand store and cache). Per topic:
- remove the user's balance and notifications subscription from
wsService(useRealTimeUpdates); - turn on
useRealtimeSync()once, in the app shell; - read the balance from the query (
useBalanceabove), not from the store fed by the WebSocket; - with realtime stable, the 10 s
refetchIntervalcan be raised or removed.
The WebSocket URL comes from wsUrl in createEnginexClient (without it, from the page's origin + /ws, through the same proxy). Predictions topics (orderbook, orders) go in useRealtimeSync({ topics }) or useRealtime, see React.
Checklist
- [ ]
ENGINEX_GATEWAY_URLset in every environment, with the value ofNEXT_PUBLIC_API_URL. - [ ] SSR tenant checked in each environment (does the
Hostarrive with the public domain?). - [ ]
trustOriginalHostonly with theproxy.tsthat covers every request that renders. - [ ]
EnginexProviderwith the player'sQueryClient(staleTime5 min). - [ ] Each piece of data migrated with readers and writers together; old keys still in
clearUserScopedQueries. - [ ] Hydrated components reading with the SDK factories (same key as the prefetch).
- [ ]
wsServicewithout balance and notifications beforeuseRealtimeSync. - [ ] No
tokenStorewithnext.revalidate, and no player data in the prefetch. - [ ] Exactly one refresh owner: phase A with
sessionOwner: 'app'andonAccessTokenRejectedin the SDK; phase B withsessionOwner: 'sdk'and the old interceptor's refresh removed. - [ ]
baseUrl/ENGINEX_GATEWAY_URLwith the origin only (no/api). - [ ] Manual idempotency removed where
useEnginexMutationalready handles it.