---
updatedAt: 2026-11-02T15:20:31.000Z
agentTools:
  projectIndex: https://docs.pley.com/llms.txt
---

# How to build a Headless Gaming Destination?

When you build your own web destination, use the Pley Web SDK to implement the game!

## Overview

Use **Pley Web SDK 2** to embed a game on a website you manage and connect authentication, player controls, payments, ads, and events.

If you want a ready-made game website instead, see [Pley Gamesites](https://docs.pley.com/docs/launching-on-a-pley-gamesite).

## 1. Configure a distribution channel

In [Game Manager](https://manage.pley.com/), open your game's **Distribution channels** and create a channel:

* **Playable:** Pley handles login. You can create multiple channels.
* **Playable with external auth:** your website handles login. One per game.

Copy the **Channel ID** from the channel's page. This is the `distributionId` passed to the SDK. The **Integration** tab also provides a snippet with the ID filled in. Scope IDs and release track IDs are not interchangeable with this ID.

Leave **Basic iframe** off to use SDK2. See [Distribution Channels & the Smart Playable URL](https://docs.pley.com/docs/distribution-channels-the-smart-playable-url).

Check these settings:

* **Mobile and tablet:** off by default; players on these devices see a device-not-supported screen. This replaces WebSDK1's `allowAllBrowsers` option.
* **Autoplay:** when off, players press a start button. Your page can also start the game with `delayedStart()`.

## 2. Load the SDK and provide a container

Load the script before initialization. The container must already exist and have explicit dimensions.

```html
<script src="https://www.pley.com/playable/v1/web_sdk2.js"></script>
<div id="game-container" style="width: 100%; height: 80vh;"></div>
```

The script exposes `Pley.WebSdk`. The URL `https://www.pley.com/playable/v1/sdk2.js` serves the same file.

## 3. Create the playable

The constructor creates the playable iframe directly; there is no separate initialization or `createPlayable()` step. For a **Playable** channel where Pley handles login:

```javascript
const playable = new Pley.WebSdk("game-container", "YOUR_CHANNEL_ID");
```

For external authentication, provide the host callbacks described in [Website-level login](https://docs.pley.com/docs/how-to-integrate-your-existing-user-system).

The SDK throws if the container cannot be found, the channel ID is empty, or it is not running in a browser. The iframe fills the container's width and height. Calls such as `updateToken()` and `setVolume()` are queued until the playable is ready.

## Host callbacks

Register callbacks in the constructor options so they are available from the start of the session. The following is a type reference; the named SDK types describe callback payloads, rather than application-provided functions.

```typescript
interface WebSdkOptions {
  initialToken?: string;
  onIssueToken?: (gameId?: string) => Promise<string | undefined>;
  onLoginRequested?: (type: "login" | "signup") => Promise<{ cancelled: boolean }>;
  onAdRequested?: (type: "unset" | "reward" | "interstitial" | "preroll") => Promise<boolean>;
  onStartPayment?: (req: StartPaymentReq, rpc: PleyCaller) => Promise<{ entitlementId: string }>;
  onGetProducts?: (req: GetProductsReq, rpc: PleyCaller) => Promise<GetProductsRes>;
  onOpenLink?: (url: string) => void;
  onSyncDialog?: (state: PepperTopBar) => void;
  onUsernameRequested?: () => Promise<string | undefined>;
  onEvent?: (event: PleyEvent) => void;
}
```

`onIssueToken`, `onLoginRequested`, `onAdRequested`, `onStartPayment`, and `onGetProducts` must return Promises. Declare these handlers `async`; synchronous return values fail because the SDK calls `.then()` on them.

### Required handlers

The playable reports the handlers its channel requires during its handshake:

* **Playable with external auth:** `onIssueToken` and `onLoginRequested`.
* **Host-supplied ads, products, or payments:** `onAdRequested`, `onGetProducts`, and/or `onStartPayment`, according to the channel configuration.
* **Pley Gamesite and Xsolla Edition gamesite:** `onSyncDialog`. Xsolla Edition gamesites also require the authentication handlers.

`onOpenLink`, `onUsernameRequested`, and `onEvent` are optional. Implement all handlers required by your channel before construction. Missing required handlers can cause the SDK to dispose itself and report a handshake error.

## Authentication

This section applies to **Playable with external auth** channels. Obtain Pley access tokens from your backend using the `issue-access-token` API. These are JWTs valid for 30 minutes; keep your backend API credentials out of browser code.

The playable requests a token on startup and when its current token is expiring. The SDK responds in this order:

1. After an explicit logout with `updateToken()`, it reports no host user without calling `onIssueToken`.
2. On the first request, it uses `initialToken`, if supplied. This initial value is used once.
3. Otherwise it calls `onIssueToken(gameId)`.
4. If the callback returns `undefined` and a token was previously set, that token is reused. Returning `undefined` is **not** a logout.
5. With no token available, it starts a guest session.

If `onIssueToken` throws, the SDK logs the error and reports authentication failure to the playable. The SDK does not refresh tokens on its own timer; return a currently valid token whenever requested.

Call `updateToken` when your website's authentication state changes:

```javascript
playable.updateToken(newAccessToken); // Login or account switch.
playable.updateToken();               // Logout and return to a guest session.
```

The method returns nothing. Passing the same token is a no-op unless it is within five minutes of expiry. Changing the user restarts the game for that user.

### Login requests from the game

`onLoginRequested` receives `"login"` or `"signup"`. Open your login UI, update your website's auth state and the playable token on success, and resolve `{ cancelled: false }`. If the player closes the UI, resolve `{ cancelled: true }` so the game stops waiting.

```javascript
// Include this callback in the constructor options.
onLoginRequested: async (type) => {
  const token = await openYourLoginDialog(type);
  if (!token) return { cancelled: true };
  playable.updateToken(token);
  return { cancelled: false };
}
```

Your external-auth integration also needs the allocate-game-user webhook to select each user's progress. See [Website-level login](https://docs.pley.com/docs/how-to-integrate-your-existing-user-system).

Account linking through the WebSDK1 `pley_connect_code` URL parameter is not forwarded by SDK2 and is not available through that flow on headless destinations.

## Player controls

```javascript
playable.updateVolume("mute");
playable.updateVolume("unmute");
playable.setVolume(0.5); // Clamped to 0.0–1.0.
playable.toggleFullscreen();
playable.delayedStart(); // Start from your page when Autoplay is off.
```

The SDK synchronizes native fullscreen changes with the playable. Where supported, it requests an Escape keyboard lock so the game can use Escape as input while fullscreen.

## Ads

Implement `onAdRequested` to show ads through your own ad provider:

```javascript
onAdRequested: async (adType) => {
  return await myAdProvider.showAd(adType); // Resolve a boolean.
}
```

Ad types are `"unset"`, `"reward"`, `"interstitial"`, and `"preroll"`. A rejected handler reports that the ad was not shown. If your website detects that ads are blocked, inform the playable:

```javascript
playable.setAdsAreBlocked(true);
```

Consent queries from the playable's ad scripts are forwarded to `window.__tcfapi` on your page. Load a TCF-compliant consent management platform where your integration requires it. Without this API, a consent query fails and the SDK reports a console error.

## Payments

Implement `onGetProducts` and `onStartPayment` to connect the game's purchases to your storefront and payment backend.

`onGetProducts` receives `{ productIds: string[], gameId: string }` and must resolve `{ payload: { products: Product[] } }`. Do not add a `res` wrapper. To start with Pley's product data:

```javascript
onGetProducts: async (req, rpc) => {
  const res = await rpc.getPleyProducts(req);
  // Optionally filter or adjust res.payload.products.
  return res;
}
```

A product includes `productId`, `name`, `image`, `gameTitle`, `prices`, `pricetierName`, `priceUsdTier`, `productSlug`, and `discordSku`. Prices include `country`, `currency`, `amount` in minor units, `amountUsd`, and `amountEur`.

`onStartPayment` receives `{ orderId: string, productIds: string[] }`. Resolve `{ entitlementId }` when the purchase completes, resolve `{ entitlementId: "" }` for cancellation, and throw on failure:

```javascript
onStartPayment: async ({ orderId, productIds }, rpc) => {
  const result = await myStore.purchase(orderId, productIds);
  if (result.cancelled) return { entitlementId: "" };
  return { entitlementId: result.entitlementId };
}
```

Both handlers receive an `rpc` helper as their second argument:

* `getPleyProducts({ productIds, gameId })` retrieves Pley product data.
* `beginDiscordPurchase(orderId, productId)` and `finishDiscordPurchase(orderId, discordEntitlementId)` are for Discord Activity destinations only.

Each RPC call times out after 120 seconds. These examples assume working host integrations; replace `myStore` and `myAdProvider` with your implementations.

## Username

Supply a display name when requested, including for guest sessions or accounts without a name on file:

```javascript
onUsernameRequested: async () => currentUser?.displayName
```

Without this handler, the game receives `undefined`.

## Dialog synchronization

The playable's top bar has connect (QR code), settings, support, controls, and resolution dialogs. If your page renders a top bar, use `onSyncDialog` to reflect changes from the playable:

```javascript
onSyncDialog: (state) => {
  // isConnectQROpen, isSettingsOpen, isSupportOpen,
  // isControlsOpen, isResolutionOpen.
  myTopBar.setState(state);
}
```

Send changes from your page back to the playable with the complete dialog state:

```javascript
playable.updatePepperTopbar({ ...myTopBar.state, isSupportOpen: true });
```

## Opening external links

```javascript
onOpenLink: (url) => {
  window.open(url, "_blank", "noopener");
}
```

## Event handling

Use `onEvent` to receive analytics and lifecycle events. Forward game events marked `channel: "external"` to your analytics integration; other game-event channels are Pley's own.

```javascript
onEvent: (event) => {
  if (event.type === "event") {
    if (event.channel === "external") {
      analytics.track(event.event, event.data);
    }
  } else {
    // loading_start, loading_stop, gameplay_start, gameplay_stop.
    analytics.track(event.type);
  }
}
```

See [Analytics from the Web Playable](https://docs.pley.com/docs/how-to-get-analytics-from-the-web-playable) and [Pley Analytics](https://docs.pley.com/docs/analytics).

For attribution, the SDK sends the playable the page referrer, UTM parameters, ad click IDs such as `gclid` and `fbclid`, hostname, and whether `onIssueToken` was supplied. Account for this in your privacy disclosures where required.

## Save data conflict detection

For **Playable with external auth** channels, detect progress in multiple scopes, such as your website (`"default"`) and CrazyGames (`"crazygames"`, matched by email), and let the player choose which progress to keep.

```javascript
const conflicts = (await playable.detectConflict()) ?? [];
if (conflicts.length > 0) {
  const chosenScopeType = await askPlayerToChooseProgress(conflicts);
  if (chosenScopeType) await playable.resolveConflict(chosenScopeType);
}
```

`askPlayerToChooseProgress` represents your own selection UI. Conflict entries have the shape `{ scopeType: string }`. The chosen scope's progress becomes the player's progress in all conflicting scopes. Pley retains a record of the previous progress for recovery through support.

* Scope types are `"default"`, `"crazygames"`, `"discord"`, and `"unknown"`. Discord conflicts are not detected on Playable with external auth channels.
* With no argument, `detectConflict()` checks all scopes. To narrow the search, pass at least two scope types, including `"default"`.
* Call `resolveConflict()` within 15 minutes of detection, using a returned scope type.
* If the chosen progress belongs to another account, your allocate-game-user webhook must return the provided `user_chosen_pley_game_user_id`; otherwise the resolution is rolled back.
* Both methods reject on error or after 120 seconds without a response.

## Cleanup

Call `dispose()` when the host component unmounts or before replacing the playable. It removes the iframe and tears down message and fullscreen listeners.

```javascript
playable.dispose();
```

## WebSdk interface

```typescript
declare class WebSdk {
  constructor(elementId: string, distributionId: string, options?: WebSdkOptions);
  readonly iframe: HTMLIFrameElement;
  updateToken(token?: string): void;
  updateVolume(volume: "mute" | "unmute"): void;
  setVolume(level: number): void;
  toggleFullscreen(): void;
  delayedStart(): void;
  setAdsAreBlocked(blocked: boolean): void;
  updatePepperTopbar(state: PepperTopBar): void;
  detectConflict(scopeTypes?: string[]): Promise<{ scopeType: string }[] | undefined>;
  resolveConflict(scopeType: string): Promise<void>;
  dispose(): void;
}
```

## React example

This external-auth example assumes that the SDK script is loaded and your application supplies its TypeScript declarations. Replace the auth store, login dialog, and analytics integration with your own implementations. `refreshToken()` must return `undefined` for guests. The login dialog must update the same auth store before resolving a successful login.

Add ad, product, and payment handlers when your channel requires host-supplied monetization.

```typescript
import { useEffect, useRef } from "react";

function GamePlayer() {
  const playableRef = useRef<InstanceType<typeof Pley.WebSdk> | null>(null);
  const { token, refreshToken, currentUser } = useAuthStore();
  const latest = useRef({ refreshToken, currentUser });
  latest.current = { refreshToken, currentUser };

  useEffect(() => {
    const playable = new Pley.WebSdk("game-container", "YOUR_CHANNEL_ID", {
      initialToken: token ?? undefined,
      onIssueToken: async () => await latest.current.refreshToken(),
      onLoginRequested: async (type) => {
        // This helper also updates the website's auth store on success.
        const newToken = await openYourLoginDialog(type);
        if (!newToken) return { cancelled: true };
        playable.updateToken(newToken);
        return { cancelled: false };
      },
      onUsernameRequested: async () => latest.current.currentUser?.displayName,
      onOpenLink: (url) => { window.open(url, "_blank", "noopener"); },
      onEvent: (event) => {
        if (event.type === "event") {
          if (event.channel === "external") analytics.track(event.event, event.data);
        } else {
          analytics.track(event.type);
        }
      },
    });
    playableRef.current = playable;

    return () => {
      playable.dispose();
      playableRef.current = null;
    };
  }, []);

  useEffect(() => {
    // undefined explicitly logs out; repeating the same token is normally a no-op.
    playableRef.current?.updateToken(token ?? undefined);
  }, [token]);

  return <div id="game-container" style={{ width: "100%", height: "100vh" }} />;
}
```

## Moving from the earlier Web SDK

| Earlier integration                                   | Web SDK 2                                                     |
| ----------------------------------------------------- | ------------------------------------------------------------- |
| `web_sdk.js`                                          | `web_sdk2.js`                                                 |
| `new Pley.Web(...)`, then `createPlayable(...)`       | `new Pley.WebSdk(containerId, distributionId, options)`       |
| Scope ID and release track ID supplied by the website | Channel ID identifies the configured channel.                 |
| `allowAllBrowsers`                                    | Channel's **Mobile and tablet** setting.                      |
| `playable.addEventHandler(...)`                       | `onEvent` in constructor options.                             |
| SDK-level token and volume updates                    | `playable.updateToken(...)` and `playable.updateVolume(...)`. |

Migrate the channel configuration and host callbacks together.