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_EXPIREDorTOKEN_STALE), the SDK renews and repeats the request once. Simultaneous requests share a single refresh. A 401 with any other code, such asINVALID_CREDENTIALSfor a wrong current password inchangePasswordordisable2fa, orUNAUTHENTICATED/TOKEN_INVALIDpassed 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 noonAccessTokenRejected. - Failure: if the refresh is refused, the session is cleared and
onSessionExpiredis 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;onSessionExpiredis 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.
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, anoptionalcall 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
onSessionExpiredis 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
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':
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.
With 'app':
- The SDK only reads the
tokenStoreto sign requests and buildsession.get(). It never callsPOST /auth/refreshand does not clear the session;onSessionExpiredis not called. auth.loginandauth.logout(and any SDK session write) reject withCONFIGURATION_ERRORbefore sending: login and logout belong to the app.- A 401 reaches the caller unrepaired (
auth: 'optional'still repeats without a token). What renews isonAccessTokenRejected. The exception: if the app already wrote a new token to thetokenStorewhile 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. autoRefreshbecomesfalse;autoRefresh: truetogether with'app'throwsCONFIGURATION_ERRORwhen the client is created. The same applies toonAccessTokenRejectedwithoutsessionOwner: 'app'(with'sdk', useonSessionExpired).
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
tokenStoredoes 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
UNAUTHENTICATEDbefore sending) nor afterclient.dispose(). An exception inside it does not change the call's error. - Realtime's
unauthorizeddoes not fireonAccessTokenRejected: 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
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.