---
url: https://game-engine-io.github.io/enginex-frontend-sdk/frameworks/next.md
---
# 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`](/frameworks/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 |

```bash
npm i @getenginex/sdk @getenginex/sdk-next @tanstack/react-query
```

Peers: `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:

```tsx
// 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>
}
```

```tsx
// 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`

```tsx
// 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>
}
```

```bash
# server .env (no NEXT_PUBLIC_)
ENGINEX_GATEWAY_URL=https://gateway.operador.com
```

* **Gateway:** the option's `baseUrl` or the `ENGINEX_GATEWAY_URL` variable, read on every request (absolute URL).
  Without either, the promise rejects with `CONFIGURATION_ERROR` before any `fetch`. If the app already has the
  URL in `NEXT_PUBLIC_API_URL`, set `ENGINEX_GATEWAY_URL` to the same value (or pass
  `baseUrl: 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 (`tags` compared by content, `resolveHost` and `tokenStore` by 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-next` in `serverExternalPackages`:** outside the server bundle, the `server-only` import
  of the `/server` entry fails and `next build` stops with the `server-only` error (verified with
  Turbopack and webpack). Let Next bundle `sdk-next`.
* **Anonymous by default:** it does not read cookies, uses an empty `memoryTokenStore()` and `autoRefresh: false`. User
  queries made with it reject with `UNAUTHENTICATED` without a request.
* **Next cache:** `next: { revalidate, tags }` goes on every `fetch` of the client; a `fetchOptions.next`
  on a call wins field by field. The Data Cache key includes the request headers, so different tenants
  (`X-Original-Host` sent 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:

1. `host`: the domain the browser requested;
2. `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`. |

::: danger `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` {#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`:

```ts
// 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).*)'],
}
```

```ts
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`:

```ts
// 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`

```tsx
// 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>
  )
}
```

* `select` receives the core factories (with the server client) or those of a product package. The keys
  are the same ones `useEnginexQuery` uses in the browser, so the component finds the hydrated data:

  ```ts
  import { 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 `QueryClient` per 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 browser `QueryClient`'s `staleTime`: the one `EnginexProvider` creates 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 (except `config.*`, which has its own `staleTime`).

## Cookie session (optional) {#cookie-session}

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:

```tsx
// 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 }) })
```

```tsx
// 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 no `Domain`. `name`, `maxAge`
  (seconds; without it, a browser session cookie) and `path` are options; use the same `name` in
  `readCookieTokenStore({ name })`. Invalid values throw `CONFIGURATION_ERROR` on 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 `UNAUTHENTICATED` until 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 the `EnginexProvider` the session read on the server (`enginex.session.get()` from the client with
  `readCookieTokenStore()`), 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 authenticated
  `initialSession` (see below).
* Outside the browser (the SSR of a Client Component), `nextCookieTokenStore` stores nothing.

### Player data: Server Component or after hydration {#player-data}

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 the `Account` in the
  [example](/guide/installation#examples). The server and
  hydration render the anonymous branch; right after, the real session appears and the component mounts. If
  `prefetchEnginex` brought the player's data (with `readCookieTokenStore()`), 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() })`, like `app/account/page.tsx` above).

* 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 |

::: warning 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](https://developer.mozilla.org/docs/Web/HTTP/Reference/Headers/Set-Cookie));
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`.
:::

::: danger 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 (the `Authorization` is part of the key), but stored on the server and
  served stale to the same player until revalidation. For player data, leave `next` out of
  `getEnginexServer` (and out of `fetchOptions.next`).
* **Prefetching player data:** with a `tokenStore`, user queries go into the `prefetchEnginex`
  state 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 `Cookie` header) 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):

```ts
'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`

```ts
// 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 in `paths`)
  **after** the app's rewrites, in an array or in `{ beforeFiles, afterFiles, fallback }` (it goes into
  `afterFiles`).
* It does not duplicate: an app rewrite with no condition and the same `source` wins. One with `has`/`missing` does not cover
  every request, and the gateway's goes in after it.
* Composes with other wrappers: accepts the config object or the `(phase, ctx) => config` function.
* Without an absolute `gatewayUrl`, it throws `CONFIGURATION_ERROR` when loading the config.
* It does not touch `x-original-host`: that belongs to the app's [`proxy.ts`](#proxy-ts-with-x-original-host).

## Testing {#testing}

* **Client Components** are tested as in [React](/frameworks/react#testing): `@getenginex/sdk-next`
  re-exports `EnginexProvider` and 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: mock `server-only`, and
  create the client with `createEnginexClient` and the mock instead of `getEnginexServer()`, which reads Next's
  `headers()` and only works inside a request. `prefetchEnginex` takes that client as it would the server one:

```ts
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](/guide/testing#product-packages-and-adapters).
