---
url: https://game-engine-io.github.io/enginex-frontend-sdk/igaming/sportsbook.md
---
# Sportsbook (FIRST)

The demo above really calls `createSession` (with `createMockFetch` and the routes of
`@getenginex/sdk-igaming/testing`) and connects the iframe with the real `connectFirstFrame`. **FIRST is
a simulation:** the frame is a static page of this site (`demos/first-frame.html`) that sends the same
`postMessage` events as FIRST. It is on the same origin as the `src`, so the helper accepts the messages
without weakening the origin check (a `srcdoc` or `about:blank` would be refused on purpose). Click the
buttons inside the frame: `BET_WAS_PLACED` reloads the balance over HTTP, `INSUFFICIENT_FUNDS` shows the
deposit CTA, `BUTTON_REDIRECT` goes through link validation (the dangerous link is refused) and the
**send** buttons send commands to the frame. The `launchUrl` has the operator token masked on screen and
in the **Under the hood** panel.

The `sportsbook` namespace of [`@getenginex/sdk-igaming`](/igaming/) creates the **sportsbook FIRST
session** of the logged-in player: the gateway generates a short-lived operator token and returns the
URL that the app loads in an iframe. `createSession` requires login (`enginex.auth.login`); the
**logged-out** visitor can also see the sportsbook, through the public URL in the configuration (see
[Logged-out visitor](#logged-out-visitor)). In tests, `withIgamingRoutes` already answers the route (see
[Testing](/igaming/#tests)).

## 1. Confirm that FIRST is active

The sportsbook configuration belongs to the core (`enginex.config.getSportsbook()`, public). The gateway
answers `400` on `createSession` when FIRST is not enabled for the operator; checking first avoids the
call and lets the screen decide what to show:

```ts
const sportsbook = await enginex.config.getSportsbook()
if (!sportsbook.enabled || sportsbook.provider !== 'first') {
  // another provider (or none): do not use createSession
}
```

## 2. Create the session

```ts
import { createIgaming } from '@getenginex/sdk-igaming'

const igaming = createIgaming(enginex)

const session = await igaming.sportsbook.createSession()
session.launchUrl // sportsbook URL, with the operator token in the query
session.expiresInSeconds // validity counted from the response (24 h on the default gateway)
session.expiresAt // ms since the epoch: client clock at the response + expiresInSeconds * 1000
```

The operator token does **not** appear in the result: it only exists inside `launchUrl`. That is why the
URL is treated as sensitive, like the casino's `gameUrl`: no hook (`onRequest`, `onResponse`, `onError`)
or `onValidationIssue` receives the URL, and the response is always validated in strict mode. A
`launchUrl` that is not an absolute http(s) URL, or an `expiresInSeconds` less than or equal to zero,
becomes `VALIDATION_ERROR`. Do not log the URL, send it to analytics or to error tracking.

## 3. Reuse until `expiresAt - 30 s`

The SDK does no caching: each call generates a new token. Keep the session in memory in the app and only
create another one close to expiry:

```ts
let session: SportsbookSession | undefined

async function currentSession() {
  if (!session || Date.now() >= session.expiresAt - 30_000) {
    session = await igaming.sportsbook.createSession()
  }
  return session
}
```

When switching users (logout/login), discard the session: the token belongs to the player who created it.

## 4. Mount the iframe

```ts
const { launchUrl } = await currentSession()
const iframe = document.createElement('iframe')
iframe.src = launchUrl
iframe.style.width = '100%'
iframe.style.border = '0'
container.append(iframe)
```

## 5. Iframe events

FIRST talks to the page through `postMessage`. The optional `connectFirstFrame` helper, from the
`@getenginex/sdk-igaming/first-frame` entry, receives these events in typed handlers and sends commands
to the iframe. It is a separate entry: whoever imports only `createIgaming` does not get it in the
bundle, and it does not import the core at runtime (nor does it require `lib.dom` in its types).

```ts
import { connectFirstFrame } from '@getenginex/sdk-igaming/first-frame'

const frame = connectFirstFrame(iframe, {
  onReady: () => frame.send('home', { value: true }),
  onBetPlaced: () => void enginex.wallet.getBalance().then(showBalance),
  onLoginRequired: () => openLoginModal(),
  onInsufficientFunds: () => goToDeposit(),
  onHeightChange: (height) => (iframe.style.height = `${height}px`),
  onRedirect: (data) => openSafely(data),
})

// when unmounting the iframe (or switching users):
frame.dispose()
```

## Logged-out visitor {#logged-out-visitor}

The FIRST iframe also loads **anonymously**: the visitor browses events and odds and, when they try to
bet, FIRST asks for login. There is no session for that: use the public URL from the configuration,
`config.sportsbookUrl` of `enginex.config.getSportsbook()` (public route, no token). This is what the
player app does.

```ts
const sportsbook = await enginex.config.getSportsbook()
const publicUrl = sportsbook.enabled && sportsbook.provider === 'first' ? sportsbook.config?.sportsbookUrl : undefined

async function sportsbookUrl(): Promise<string | undefined> {
  // logged in: the player's session (with the operator token); visitor: public URL, no token
  if (enginex.session.get().status === 'authenticated') return (await currentSession()).launchUrl
  return publicUrl
}

iframe.src = (await sportsbookUrl()) ?? 'about:blank'

const frame = connectFirstFrame(iframe, {
  // PLACE_BET_CLICKED_NOT_LOGGED_IN or OPEN_LOGIN_POPUP: the visitor tried to bet
  onLoginRequired: () => openLoginModal(),
})

// after login (and on logout), swap the URL of the same iframe
let userId = enginex.session.get().userId
enginex.session.subscribe(async (current) => {
  if (current.userId === userId) return // token refresh for the same user: nothing changes
  userId = current.userId
  session = undefined // the FIRST session belongs to the player who created it
  iframe.src = (await sportsbookUrl()) ?? 'about:blank'
})
```

* **Before login** no authenticated call is made: `createSession()` with no session rejects with
  `UNAUTHENTICATED` without a request.
* **After login**, call `createSession()` and swap the `src` for the `launchUrl`. `connectFirstFrame`
  rereads the `src` origin on every message, so the same `frame` keeps working; FIRST reloads and sends
  `APP_READY` again.
* Treat the configuration's `sportsbookUrl` like any received URL: use it only if it is an absolute
  http(s) URL without credentials. If your configuration also carries `config.widgetUrl`, the player app
  passes it to FIRST in the `api` parameter of the public URL (`url.searchParams.set('api', widgetUrl)`),
  only when it is `https`.
* The public URL does **not** carry an operator token. Do not reuse an old `launchUrl` for the visitor:
  it is a player's session.

### Security

The helper only delivers a message if `event.source === iframe.contentWindow` **and** `event.origin` is
the origin of `iframe.src` (reread on every message). A different origin, another window, invalid JSON
or a message without `eventType` are ignored, without throwing. `send` always posts to the `src` origin,
never to `'*'`: if the `src` has no valid http(s) origin, or after `dispose()`, it throws
`CONFIGURATION_ERROR` (without including the `src`, which carries the token). A handler that throws
does not bring down the listener nor stop the others. Payloads arrive as `unknown`, exactly as FIRST sent
them: validate before using. In particular, `onRedirect` receives `{ link?: string }` (the `link` may be
missing; a `link` that is not a string is dropped by the helper): open the link only if it exists, is
http(s) and has no credentials (`window.open(link, '_blank', 'noopener,noreferrer')`).

By default the helper listens on `globalThis` (the window of the page that contains the iframe); pass
`{ window }` as the third argument for another window or outside the browser.

### Events received

The event comes in `eventType` (the helper also accepts the `type` key). `onEvent(eventType, eventData)`
is called for **every** accepted event, including those with a dedicated handler.

| FIRST event (`eventType`) | Handler | Argument |
| --- | --- | --- |
| `APP_READY` | `onReady()` | none |
| `BET_WAS_PLACED` | `onBetPlaced(data)` | `eventData` |
| `INSUFFICIENT_FUNDS` | `onInsufficientFunds(data)` | `eventData` |
| `depositClick` | `onDepositClick(data)` | `eventData` |
| `PLACE_BET_CLICKED_NOT_LOGGED_IN`, `OPEN_LOGIN_POPUP` | `onLoginRequired(data)` | `eventData` |
| `on-page-height-change`, `ON_PAGE_HEIGHT_CHANGE` | `onHeightChange(height)` | `eventData.height` (or `height` at the top of the message); positive numbers only |
| `BUTTON_REDIRECT` | `onRedirect(data)` | `{ link?: string }` (the `link` comes at the top of the message and may be missing) |
| `SCROLL_TO_TOP` | `onScrollToTop()` | none |
| `bet-in-process`, `BET_IN_PROCESS`, `reserve-error`, `UPDATE_BETS_COUNT`, `BETSLIP_OPEN`, `BETSLIP_CLOSE`, `shareBetslip` (`{ code }`), `LOCATION_CHANGE`, `POPUP_STATE_CHANGE`, `LANGUAGE_CHANGED`, `languageChange`, `messageToParent` | `onEvent` only | `eventData` |

### Commands sent

`frame.send(eventType, eventData?)` posts `{ eventType, eventData }` (as JSON) to the iframe. Wait for
`onReady` before sending: FIRST only listens after it has loaded. The commands FIRST understands:

| `eventType` | `eventData` |
| --- | --- |
| `sportId`, `leagueId`, `eventId` | `{ value: id }` |
| `liveBetting`, `home` | `{ value: true }` |
| `betting-history`, `open-bets`, `expand-bet-slip` | `{ value: boolean }` |
| `bscode` | `{ value: code }` (loads a shared bet slip) |
| `shareBetslip` | `{ url }` (reply to the received `shareBetslip`) |

## Errors

| Code | When |
| --- | --- |
| `UNAUTHENTICATED` | no session (no request is made); for the visitor, use the [public URL](#logged-out-visitor) |
| `INVALID_ARGUMENT` (400) | FIRST not enabled for the operator (use the envelope's code) |
| `UNAVAILABLE` (503) | incomplete FIRST configuration, session service down or the betting service's sportsbook configuration unavailable |
| `VALIDATION_ERROR` | `launch_url` not an absolute http(s) URL or `expires_in_seconds` not positive |

Identify by the code: `isEnginexError(error, 'UNAVAILABLE')`.

## Testing {#tests}

The mock route `GET /first/session` (logged in) returns `https://first.mock.local/sportsbook?operatorToken=...`
with a 24 h validity and a new token on every call.
