Next.js
@getenginex/sdk-next is the App Router adapter. It has three entries:
| Entry | Where it runs | What it provides |
|---|---|---|
@getenginex/sdk-next | Client Components | everything in @getenginex/sdk-react and nextCookieTokenStore (cookie session, optional) |
@getenginex/sdk-next/server | Server Components, Server Actions, Route Handlers (server-only) | getEnginexServer, prefetchEnginex and readCookieTokenStore |
@getenginex/sdk-next/config | next.config.ts | withEnginex, the /api/:path* → gateway rewrite |
npm i @getenginex/sdk @getenginex/sdk-next @tanstack/react-queryPeers: next >=15, react >=19, @tanstack/react-query ^5 and @getenginex/sdk >=0.6.0 <1.0.0. sdk-react comes as a dependency (same version as sdk-next). Importing @getenginex/sdk-next/server in a Client Component breaks the build (server-only).
The model is the players': anonymous, per-tenant SSR (configuration, catalog, CMS), the session in the browser (localStorage) and the browser calling the gateway on the same origin (/api, via rewrite).
Client
The provider is the same as React's. Create the browser client in a 'use client' module:
// app/providers.tsx
'use client'
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { EnginexProvider } from '@getenginex/sdk-next'
const enginex = createEnginexClient({ locale: 'pt-BR', tokenStore: localStorageTokenStore() })
export function Providers({ children }: { children: React.ReactNode }) {
return <EnginexProvider client={enginex}>{children}</EnginexProvider>
}// app/layout.tsx
import { Providers } from './providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="pt-BR">
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}In the browser the SDK calls /api/v1/... on the same origin and sends the page's domain as the tenant; the rewrite (below) takes the request to the gateway.
Server: getEnginexServer
// app/page.tsx (Server Component)
import { getEnginexServer } from '@getenginex/sdk-next/server'
export default async function Page() {
const enginex = await getEnginexServer({ next: { revalidate: 300, tags: ['config'] } })
const config = await enginex.config.get()
return <p>Currency: {config.defaultCurrency}</p>
}# server .env (no NEXT_PUBLIC_)
ENGINEX_GATEWAY_URL=https://gateway.operador.com- Gateway: the option's
baseUrlor theENGINEX_GATEWAY_URLvariable, read on every request (absolute URL). Without either, the promise rejects withCONFIGURATION_ERRORbefore anyfetch. If the app already has the URL inNEXT_PUBLIC_API_URL, setENGINEX_GATEWAY_URLto the same value (or passbaseUrl: process.env.NEXT_PUBLIC_API_URL). - One client per request, memoized with React's
cache(): within the same request, equal options return the same client (tagscompared by content,resolveHostandtokenStoreby reference, so define them outside the component). Different requests never share a client, and there is no module-scope client. Outside a React render (Route Handler), each call creates a new client. - Do not put
sdk-nextinserverExternalPackages: outside the server bundle, theserver-onlyimport of the/serverentry fails andnext buildstops with theserver-onlyerror (verified with Turbopack and webpack). Let Next bundlesdk-next. - Anonymous by default: it does not read cookies, uses an empty
memoryTokenStore()andautoRefresh: false. User queries made with it reject withUNAUTHENTICATEDwithout a request. - Next cache:
next: { revalidate, tags }goes on everyfetchof the client; afetchOptions.nexton a call wins field by field. The Data Cache key includes the request headers, so different tenants (X-Original-Hostsent to the gateway) and tokens (Authorization) never share a response. - Reading
headers()makes the route dynamic, like any per-tenant data.
Tenant
The operator's domain comes from headers(), in this order:
host: the domain the browser requested;x-forwarded-host: last resort.
This is what the players already do in SSR. From a list (a.com, internal.proxy), the first value is used; the port stays as it came (the gateway removes it). With neither, it rejects with CONFIGURATION_ERROR.
| Option | Effect |
|---|---|
trustOriginalHost: true | x-original-host now comes before host. Only with a proxy.ts that overwrites it on every request that renders (below). |
resolveHost(headers) | replaces the discovery entirely (ignores the order and trustOriginalHost); returning undefined rejects with CONFIGURATION_ERROR. |
x-original-host comes from the browser
On a page request, x-original-host arrives as the browser sent it: the players' proxy.ts only overwrites it on /api and /dev. Trusting it without a proxy.ts that writes it on every request would let anyone choose the SSR operator: one domain's page would render with another operator's configuration, catalog and CMS (and, with next.revalidate, store those responses in the Data Cache).
proxy.ts with x-original-host
The gateway finds the operator by X-Original-Host. Browser requests go through the /api rewrite, and the app's proxy.ts (the middleware.ts before Next 16) writes the header with the page's host. To also turn on trustOriginalHost, the proxy.ts must overwrite the header on every request that renders, not just on /api:
// src/proxy.ts
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const headers = new Headers(request.headers)
const host = 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).*)'],
}const enginex = await getEnginexServer({ trustOriginalHost: true })If an ingress rewrites the Host to an internal name (e.g. player.default.svc.cluster.local), the default order picks up that name. In that case use resolveHost with the header where the ingress stores the public domain, or write that header as x-original-host in the proxy.ts above (in place of host) and turn on trustOriginalHost:
// outside the component, so the client is reused within the same request
const publicHost = (headers: Headers) => headers.get('x-forwarded-host')?.split(',')[0]?.trim()
const enginex = await getEnginexServer({ resolveHost: publicHost })Check in production which header carries the public domain before choosing: it depends on the ingress.
Prefetch: prefetchEnginex
// app/layout.tsx (Server Component)
import { HydrationBoundary } from '@tanstack/react-query'
import { getEnginexServer, prefetchEnginex } from '@getenginex/sdk-next/server'
import { Providers } from './providers'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const enginex = await getEnginexServer({ next: { revalidate: 300 } })
const state = await prefetchEnginex(enginex, (q) => [q.config.get(), q.config.getProducts()])
return (
<html lang="pt-BR">
<body>
<Providers>
<HydrationBoundary state={state}>{children}</HydrationBoundary>
</Providers>
</body>
</html>
)
}selectreceives the core factories (with the server client) or those of a product package. The keys are the same onesuseEnginexQueryuses in the browser, so the component finds the hydrated data:tsimport { createIgaming } from '@getenginex/sdk-igaming' import { createIgamingQueries } from '@getenginex/sdk-igaming/query' const igaming = createIgaming(await getEnginexServer({ next: { revalidate: 300, tags: ['catalog'] } })) const state = await prefetchEnginex(createIgamingQueries(igaming), (ig) => [ ig.casino.listCategories(), ig.casino.listProviders(), ])A new
QueryClientper call, no retry, discarded at the end (nothing stays between requests).A factory that fails does not take down the others and stays out of the state: only successful queries are dehydrated, never an error. The browser fetches the missing ones. With the anonymous client, user queries are left out (no request).
staleTime: the dehydrated state carries only the key and the data. What decides whether the browser fetches again as soon as it mounts is the browserQueryClient'sstaleTime: the oneEnginexProvidercreates uses 60 s; in yours, use one above zero (the players use 5 min). With TanStack's default (0), the browser refetches everything right after hydrating (exceptconfig.*, which has its ownstaleTime).
Cookie session (optional)
The default is still the session in localStorage and anonymous SSR. With a cookie session, the server reads it too, for pages with player data rendered on the server:
// app/providers.tsx
'use client'
import { createEnginexClient } from '@getenginex/sdk'
import { nextCookieTokenStore } from '@getenginex/sdk-next'
const enginex = createEnginexClient({ tokenStore: nextCookieTokenStore({ maxAge: 60 * 60 * 24 * 30 }) })// app/account/page.tsx (Server Component)
import { getEnginexServer, readCookieTokenStore } from '@getenginex/sdk-next/server'
export default async function Account() {
const enginex = await getEnginexServer({ tokenStore: await readCookieTokenStore() })
const balance = await enginex.wallet.getBalance()
return <p>Balance: {balance.realBalance}</p>
}- Cookie:
getenginex.tokens=<tokens>; Path=/; SameSite=Lax; Secure, with noDomain.name,maxAge(seconds; without it, a browser session cookie) andpathare options; use the samenameinreadCookieTokenStore({ name }). Invalid values throwCONFIGURATION_ERRORon creation. - No
HttpOnly, on purpose: the session refresh and the WebSocket's?token=need the token in JavaScript. - The server only reads: Server Components do not write cookies. The browser is what renews and rewrites the session; an expired access token makes server calls fail with
UNAUTHENTICATEDuntil then. initialSession: only for the part of the screen that depends only on the session (header with a log out button, the player menu): pass theEnginexProviderthe session read on the server (enginex.session.get()from the client withreadCookieTokenStore()), in a Client Component that receives it via prop, and the server and hydration render the same session. Do not wrap components that render SDK user queries during SSR with an authenticatedinitialSession(see below).- Outside the browser (the SSR of a Client Component),
nextCookieTokenStorestores nothing.
Player data: Server Component or after hydration
The factories build a user query's key from the browser client's session (client.session), not from initialSession. In the SSR of a Client Component that client has no session (nextCookieTokenStore reads nothing without document), so q.wallet.getBalance() rendered on the server uses the 'anonymous' key: the HTML comes out without the prefetched data and hydration fails (the browser renders the player's key, with the data). Therefore:
In Client Components, render user queries only after hydration: gate the component on an authenticated
useSession(), with the default (anonymous)initialSession, like theAccountin the example. The server and hydration render the anonymous branch; right after, the real session appears and the component mounts. IfprefetchEnginexbrought the player's data (withreadCookieTokenStore()), that first client render already uses it, with no request.tsx'use client' function Account() { const session = useSession() return session.status === 'authenticated' ? <Wallet /> : <LoginForm /> }In the server's HTML, render player data in a Server Component (
getEnginexServer({ tokenStore: await readCookieTokenStore() }), likeapp/account/page.tsxabove).The hydrated data belongs to the cookie's user: a browser whose session belongs to another user builds that user's key and fetches their own data; the first user's data never shows.
Cookie vs localStorage
localStorageTokenStore (default) | nextCookieTokenStore | |
|---|---|---|
| XSS | reads the token | reads the token (same: no HttpOnly) |
| Server sees the session | no (anonymous SSR) | yes, with readCookieTokenStore() |
| Sent on every request to the app | no | yes (including navigations coming from another site, with SameSite=Lax) |
| CSRF | no risk | the app's server should only use the cookie for reads, never perform actions because of it |
| Size | no practical limit | ~4 KB (both tokens in one cookie) |
| Other tabs | storage event | Cookie Store API, when the browser has it |
HTTP outside localhost | works | does not work (the browser drops the Secure cookie); on http://localhost, only where the browser makes an exception (Chrome 89+, Firefox 75+) |
| Logs | does not appear | the refresh token goes on every request to Next, to proxies and to the CDN |
HTTP in development
With Secure, every browser silently drops the cookie on an HTTP origin that is not localhost: a local network IP (http://192.168.0.10:3000) or a development host such as http://dev.operador.com:3002. Even http://localhost is only an exception where the browser makes one: Chrome (89+) and Firefox (75+) accept a Secure cookie set by localhost (see the note on the Secure attribute in Set-Cookie, on MDN); other browsers, such as Safari, may not accept it: test in yours. The browser also drops cookies above ~4 KB. In both cases set checks that the cookie stuck and, if not, warns with console.warn (without the token) and does not throw: the login is not stored. To test outside localhost, use HTTPS (next dev --experimental-https) or localStorageTokenStore.
Player data in the cache and in the HTML
tokenStore+next.revalidate: the player's responses (balance, profile, transactions) go into Next's Data Cache. They are kept separate per token (theAuthorizationis part of the key), but stored on the server and served stale to the same player until revalidation. For player data, leavenextout ofgetEnginexServer(and out offetchOptions.next).- Prefetching player data: with a
tokenStore, user queries go into theprefetchEnginexstate and, with it, into the page's HTML (in the serialized state, even if the component only renders them after hydration, as above). Only do this on pages that are never cached and served to other users (neither by Next nor by a CDN). - Logs: remove the cookie (or the
Cookieheader) from the access logs of Next, the ingress and the CDN.
Migrating from localStorage to the cookie
Swap the tokenStore and, once, copy the existing session. Only delete the old copy after checking that the cookie stuck (on an origin without HTTPS it does not, and the session would be lost):
'use client'
import { createEnginexClient, localStorageTokenStore } from '@getenginex/sdk'
import { nextCookieTokenStore } from '@getenginex/sdk-next'
const cookie = nextCookieTokenStore()
const legacy = localStorageTokenStore()
const tokens = legacy.get()
if (tokens && !cookie.get()) cookie.set(tokens)
if (tokens && cookie.get()?.refreshToken === tokens.refreshToken) legacy.clear()
export const enginex = createEnginexClient({ tokenStore: cookie })next.config.ts: withEnginex
// next.config.ts
import type { NextConfig } from 'next'
import { withEnginex } from '@getenginex/sdk-next/config'
const nextConfig: NextConfig = { reactStrictMode: true }
export default withEnginex(nextConfig, {
gatewayUrl: process.env.NEXT_PUBLIC_API_URL!,
paths: ['/api/:path*', '/dev/:path*'], // default: ['/api/:path*']
})- Adds
{ source: '/api/:path*', destination: '<gatewayUrl>/api/:path*' }(one per item inpaths) after the app's rewrites, in an array or in{ beforeFiles, afterFiles, fallback }(it goes intoafterFiles). - It does not duplicate: an app rewrite with no condition and the same
sourcewins. One withhas/missingdoes not cover every request, and the gateway's goes in after it. - Composes with other wrappers: accepts the config object or the
(phase, ctx) => configfunction. - Without an absolute
gatewayUrl, it throwsCONFIGURATION_ERRORwhen loading the config. - It does not touch
x-original-host: that belongs to the app'sproxy.ts.
Testing
- Client Components are tested as in React:
@getenginex/sdk-nextre-exportsEnginexProviderand the hooks, and the core mocks (createMockFetch,createMockRealtime) stand in for the gateway. - Server code (
@getenginex/sdk-next/server) runs in Vitest with two adjustments: mockserver-only, and create the client withcreateEnginexClientand the mock instead ofgetEnginexServer(), which reads Next'sheaders()and only works inside a request.prefetchEnginextakes that client as it would the server one:
import { createEnginexClient } from '@getenginex/sdk'
import { createMockFetch } from '@getenginex/sdk/testing'
import { prefetchEnginex } from '@getenginex/sdk-next/server'
import { expect, it, vi } from 'vitest'
// The server entry imports `server-only`, which throws outside a React Server Component.
vi.mock('server-only', () => ({}))
it('prefetches the operator configuration', async () => {
// In place of getEnginexServer(), which needs Next's request headers.
const enginex = createEnginexClient({
baseUrl: 'https://gateway.test',
tenantHost: 'casino.test',
fetch: createMockFetch(),
})
const state = await prefetchEnginex(enginex, (q) => [q.config.get(), q.config.getProducts()])
expect(state.queries.map((query) => query.state.status)).toEqual(['success', 'success'])
})For product factories, add their routes to the mock (createMockFetch(withIgamingRoutes())) and pass the factories: prefetchEnginex(createIgamingQueries(createIgaming(enginex)), (ig) => [ig.casino.listGames()]). See Testing and mocks.