---
url: https://game-engine-io.github.io/enginex-frontend-sdk/concepts/session.md
---
# Session and tokens

Login returns an **access token** (a short-lived JWT) and a **refresh token**. The SDK stores both
in a `TokenStore` and takes care of renewal:

* **Proactive:** before each request, if less than 2 minutes remain until the access token expires, the SDK renews first.
* **Reactive:** if the gateway responds 401 because of the token (a 401 without a code, as the gateway's auth middleware answers a missing, expired or invalid token, or one with `TOKEN_EXPIRED` or `TOKEN_STALE`), the SDK renews and repeats the request **once**. Simultaneous requests share a single refresh. A 401 with any other code, such as `INVALID_CREDENTIALS` for a wrong current password in `changePassword` or `disable2fa`, or `UNAUTHENTICATED`/`TOKEN_INVALID` passed through from a service (e.g. a wrong verification code), reaches the app as is: no refresh, no retry (the password is not sent twice) and no `onAccessTokenRejected`.
* **Failure:** if the refresh is refused, the session is cleared and `onSessionExpired` is called.
* **Transient failure:** if the refresh fails due to network/timeout or the response comes back without valid tokens (`VALIDATION_ERROR`), the current tokens are kept and the request fails with that error; `onSessionExpired` is not called.

## Server clients: `autoRefresh: false`

Server clients (RSC/SSR) should use `autoRefresh: false`; renewal is left to the browser or
to a Route Handler.

```ts
const enginex = createEnginexClient({
  baseUrl: 'https://gateway.operador.com',
  tenantHost: 'casino.operador.com',
  autoRefresh: false,
})
```

With `autoRefresh: false`, neither the proactive refresh (before a request, with the access token about to
expire) nor the reactive one (after a 401) calls `POST /auth/refresh`:

* The stored access token is used as is.
* A 401 reaches the caller unrepaired: `auth: 'required'` rejects with the gateway's original error; `auth: 'optional'` repeats without a token — that is, an `optional` call with an expired token costs **two requests** (the 401 and the retry without a token), instead of a refresh.
* The local session is not cleared and `onSessionExpired` is not called — the server should not decide that through a client that does not own the session.

A per-request server client normally reads the access token from an httpOnly cookie (via a custom
`tokenStore`) and never needs to renew it: that is done by the browser (with the default
client, `autoRefresh: true`) or a dedicated Route Handler.

## When the app owns the session {#app-owned-session}

An app that already has its own authentication (a store with login, refresh and logout) does not want the SDK to
renew or write tokens: two renewers exchanging the same refresh token bring the session down. Declare this
with `sessionOwner: 'app'`:

```ts
import { createEnginexClient } from '@getenginex/sdk'
import { useAuthStore } from '@/stores/auth' // your store: login, logout and refresh belong to the app
import { authStoreTokens } from '@/lib/auth-tokens' // a TokenStore over the app's store

export const enginex = createEnginexClient({
  sessionOwner: 'app',
  tokenStore: authStoreTokens,
  // The gateway refused the current access token: the app renews and writes the new tokens to the store.
  onAccessTokenRejected: () => void useAuthStore.getState().refreshSession(),
})
```

`authStoreTokens` is a `TokenStore` over the app's store: the example is in
[Migrating a Next player](/frameworks/migrating-next-player#token-store).

With `'app'`:

* The SDK only **reads** the `tokenStore` to sign requests and build `session.get()`. It never calls
  `POST /auth/refresh` and does not clear the session; `onSessionExpired` is not called.
* `auth.login` and `auth.logout` (and any SDK session write) reject with
  `CONFIGURATION_ERROR` **before** sending: login and logout belong to the app.
* A 401 reaches the caller unrepaired (`auth: 'optional'` still repeats without a token). What renews is
  `onAccessTokenRejected`. The exception: if the app already wrote a new token to the `tokenStore` while the request
  was in flight, the SDK repeats **once** with the new token (without renewing or writing anything), and the late 401
  does not reach the caller nor notify the app.
* `autoRefresh` becomes `false`; `autoRefresh: true` together with `'app'` throws `CONFIGURATION_ERROR`
  when the client is created. The same applies to `onAccessTokenRejected` without `sessionOwner: 'app'` (with `'sdk'`,
  use `onSessionExpired`).

`onAccessTokenRejected` is called with no arguments when the gateway refuses (401 because of the token, as above) the **current** access token:

* **Once per token.** A burst of 401s with the same token (several parallel queries) notifies only
  once; a late 401 from a token that was already replaced in the `tokenStore` does not notify (the request is repeated with the
  new token). If the new token is also refused, it notifies again.
* It also fires on `auth: 'optional'` calls (e.g. `config.get`), even when the retry without a token
  succeeds.
* It does not fire without a token (the `UNAUTHENTICATED` before sending) nor after `client.dispose()`. An
  exception inside it does not change the call's error.
* **Realtime**'s `unauthorized` does not fire `onAccessTokenRejected`: the WebSocket connection reports through its
  own status (`useRealtimeStatus`), and the session remains the app's. Renew the token through the same
  path as the app and the reconnection uses the new token.

The `onError` hook remains for observability (one per call that fails), not for renewal.

## Where to store the tokens

| Store | Survives reload | Across tabs | Note |
|---|---|---|---|
| `memoryTokenStore()` (default) | no | no | Safer against XSS; the player logs in again on reload. |
| `localStorageTokenStore()` | yes | yes | Readable by any script on the page: use with a Content-Security-Policy. |
| Custom | depends | depends | Implement `TokenStore` (`get`, `set`, `clear`, `subscribe`). |

`localStorageTokenStore` synchronizes tabs: if another tab renews the tokens, this tab uses the new ones
instead of spending a refresh token that was already exchanged.

## Observing the session

```ts
enginex.session.get() // { status: 'authenticated', userId, operatorId, sessionId, expiresAt }
const off = enginex.session.subscribe((s) => console.log(s.status))
```

`session.get()` returns a frozen object with the **same reference** while the session does not change (a
rotation of only the refresh token does not count), and a new reference when it changes — you can use it directly
with `useSyncExternalStore(enginex.session.subscribe, enginex.session.get)` in React, with no
re-render loop.

`createEnginexClient({ onSessionChange })` is a shortcut for `session.subscribe`.

App callbacks (`onSessionChange`, `onSessionExpired`, `onValidationIssue`, `subscribe` listeners and
those of the `TokenStore`) never break an SDK operation: if one of them throws, the login,
logout or request carry on normally and the error is rethrown in a microtask, so it still shows up
in the console and in your error tracker.
