> ## Documentation Index
> Fetch the complete documentation index at: https://docs.streampixel.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Cookbook

> Short, complete recipes for the Streampixel Web SDK: your own loading screen, a queue display, a reconnecting banner, an idle warning, a React hook, a start button, a stats readout and screenshots.

Advanced For developers who build their own interface around a stream. Each recipe is a small, complete piece that you can copy. Each one says which level it suits.

| Recipe | Level | Built from |
| - | - | - |
| [Your own loading screen](#your-own-loading-screen) | Intermediate | `state`, `progress`, `stream.streamConfig` |
| [A queue position display](#a-queue-position-display) | Intermediate | `queue` |
| [A reconnecting banner](#a-reconnecting-banner) | Advanced | `state` (`reconnecting`, `recovering`) |
| [An idle warning](#an-idle-warning) | Intermediate | `afkWarning` |
| [A React hook](#a-react-hook) | Intermediate | `create()` with `signal` |
| [Start on a button press](#start-on-a-button-press) | Beginner | `Streampixel.preload()`, `create()` |
| [A stats readout](#a-stats-readout) | Intermediate | `stats` |
| [Saving a screenshot](#saving-a-screenshot) | Beginner | `captureScreenshot()`, `screenshot` |
| [Start again after the session ends](#start-again-after-the-session-ends) | Intermediate | `ended`, `destroy()` |
| [Pass the page address to your application](#pass-the-page-address-to-your-application) | Beginner | `launchParams` |
| [Link a session to your own user](#link-a-session-to-your-own-user) | Advanced | `session` |

## The page the recipes start from

Every recipe adds a few elements and a few lines to this page. Two recipes replace `main.js` and say so.

```html title="index.html" theme={"dark"}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>My stream</title>
    <style>
      #player  { position: relative; width: 100%; max-width: 1280px; aspect-ratio: 16 / 9; background: #000; }
      #stream  { width: 100%; height: 100%; }
      .over    { position: absolute; inset: 0; z-index: 50; display: grid; place-items: center;
                 text-align: center; color: #fff; background: rgba(0, 0, 0, 0.75); }
      .banner  { position: absolute; top: 12px; left: 50%; transform: translateX(-50%); z-index: 60;
                 padding: 8px 14px; border-radius: 8px; color: #fff; background: #b45309; }
      .stats   { position: absolute; top: 12px; left: 12px; z-index: 60; margin: 0; padding: 8px 10px;
                 color: #fff; background: rgba(0, 0, 0, 0.7); font: 12px/1.5 monospace; }
      [hidden] { display: none !important; }
    </style>
  </head>
  <body>
    <div id="player">
      <div id="stream"></div>
      <!-- the recipes add their elements here -->
    </div>
    <script type="module" src="./main.js"></script>
  </body>
</html>
```

```js title="main.js" theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

const container = document.getElementById('stream');
const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });

// the recipes add their code here
```

Three things the recipes rely on:

* **Keep `#stream` empty.** The SDK adds and removes its own element there. Your elements go in `#player`, next to it.
* **The recipes leave out the `try` and `catch` around `create()`.** What it rejects with is on [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md).
* **No build tools?** Load `https://js.streampixel.io/v2/loader.js` with a script tag, and replace the `import` line with `const { Streampixel } = StreampixelSDK;`. See [Installation](https://docs.streampixel.io/resources/web-sdk-v2/installation.md).

> [!TIP]
>
> You can mix your own parts with the ready-made ones. Mount [`@streampixel/ui`](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays) and switch off only what you replace: `mountUI(stream, { container, loading: false })` for the loading recipes, `afk: false` for the idle warning.

## Your own loading screen

Intermediate Shows a message until the video plays, and again whenever the stream is not playing. Uses the project's own loading texts and logo from the dashboard.

```html title="Add inside #player" theme={"dark"}
<div id="loading" class="over">
  <div>
    <img id="loading-logo" alt="" height="48" hidden />
    <p id="loading-text">Connecting…</p>
  </div>
</div>
```

```js title="Add to main.js" expandable theme={"dark"}
const loading = document.getElementById('loading');
const loadingText = document.getElementById('loading-text');

function showLoading(text) {
  loadingText.textContent = text;
  loading.hidden = false;
}

function onState(s) {
  switch (s.kind) {
    case 'idle':
    case 'connecting':   showLoading('Connecting…'); break;
    case 'queued':       showLoading(s.position ? `In queue: position ${s.position}` : 'In queue'); break;
    case 'reconnecting': showLoading(s.waitingForHost ? 'Waiting for the host…' : 'Reconnecting…'); break;
    case 'recovering':   showLoading('Restarting the stream…'); break;
    case 'ended':        showLoading(s.message); break;
    default:             loading.hidden = true;   // streaming, awaitingPlay, awaitingPassword, or a newer kind
  }
}
stream.on('state', onState);
onState(stream.state);   // the state that is already there

// The steps inside 'connecting', with the project's loading texts one, two and three
stream.on('progress', ({ stage }) => {
  const cfg = stream.streamConfig;
  const text = { offer: cfg.loadingTextOne, answer: cfg.loadingTextTwo, connected: cfg.loadingTextThree }[stage];
  if (text) loadingText.textContent = text;
});

// The project's logo. A project without one holds a placeholder word, not an address.
const logoUrl = stream.streamConfig.customLogo;
if (typeof logoUrl === 'string' && logoUrl.startsWith('https://')) {
  const logo = document.getElementById('loading-logo');
  logo.src = logoUrl;
  logo.hidden = false;
}
```

> [!TIP]
>
> You see "Connecting…", then your project's loading texts, then the video. Stop your network for a few seconds and the screen comes back with "Reconnecting…".

> [!WARNING]
>
> This screen hides itself in `awaitingPlay` and `awaitingPassword`. Those states need their own controls: a ["Click to start" button](https://docs.streampixel.io/resources/web-sdk-v2/controls-and-input.md#when-the-browser-blocks-autoplay) and a [password form](https://docs.streampixel.io/resources/web-sdk-v2/access.md#password-projects). Without your own, mount `@streampixel/ui` with `loading: false`.

## A queue position display

Intermediate Tells a waiting viewer where they are. The server sends a new position as the queue moves.

```html title="Add inside #player" theme={"dark"}
<div id="queue" class="banner" hidden></div>
```

```js title="Add to main.js" theme={"dark"}
const queueBox = document.getElementById('queue');

stream.on('queue', ({ position }) => {
  // position is a whole number; 0 means the server did not say
  queueBox.textContent = position > 0 ? `You are number ${position} in the queue` : 'You are in the queue';
});

stream.on('state', (s) => {
  queueBox.hidden = s.kind !== 'queued';   // the state leaves 'queued' when the application answers
});
```

> [!TIP]
>
> When no GPU is free, the banner shows the viewer's place in the queue and follows it as the queue moves. It disappears when the application starts.

## A reconnecting banner

Advanced A small banner with a countdown, instead of a full loading screen. It suits a reconnect: the last picture often stays on screen while the SDK restores the connection.

```html title="Add inside #player" theme={"dark"}
<div id="reconnect" class="banner" hidden></div>
```

```js title="Add to main.js" theme={"dark"}
const reconnect = document.getElementById('reconnect');
let reconnectTick;

stream.on('state', (s) => {
  clearInterval(reconnectTick);

  if (s.kind === 'reconnecting') {
    const update = () => {
      const secondsLeft = Math.max(0, Math.round((s.deadlineMs - Date.now()) / 1000));
      reconnect.textContent = s.waitingForHost
        ? `Waiting for the host… ${secondsLeft} s`
        : `Reconnecting, try ${s.attempt}… ${secondsLeft} s`;
    };
    update();
    reconnectTick = setInterval(update, 1000);
    reconnect.hidden = false;
  } else if (s.kind === 'recovering') {
    reconnect.textContent = 'Restarting the stream…';
    reconnect.hidden = false;
  } else {
    reconnect.hidden = true;
  }
});
```

| State | What the viewer should understand |
| - | - |
| `reconnecting` | An interruption. The session is the same one. `deadlineMs` is when the SDK gives up. With `waitingForHost`, a viewer of a shared session is waiting for the host's application. |
| `recovering` | The application is started again. What the viewer did in it is lost. |

When the SDK gives up, the state is `ended` and the banner hides. Show the end message: see [Start again after the session ends](#start-again-after-the-session-ends). What leads to each state is on [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md#reconnection-and-recovery).

## An idle warning

Intermediate Warns the viewer before an idle session is closed, and lets them stay.

```html title="Add inside #player" theme={"dark"}
<div id="idle" class="over" hidden>
  <div>
    <p>Are you still there? This session closes in <span id="idle-seconds"></span> seconds.</p>
    <button id="idle-stay">I'm still here</button>
  </div>
</div>
```

```js title="Add to main.js" theme={"dark"}
const idle = document.getElementById('idle');
const idleSeconds = document.getElementById('idle-seconds');
let stay = null;

stream.on('afkWarning', (w) => {
  if (w.kind === 'countdown') {            // the countdown started, or moved on one second
    idleSeconds.textContent = String(w.secondsRemaining);
    stay = w.dismiss;
    idle.hidden = false;
  } else {                                 // 'dismissed': the viewer did something
    idle.hidden = true;
  }
});

document.getElementById('idle-stay').addEventListener('click', () => {
  stay?.();                                // the same as stream.keepAlive()
  idle.hidden = true;
});

stream.on('ended', () => { idle.hidden = true; });   // nothing stays on top of your end message
```

> [!TIP]
>
> Leave the stream alone for the project's idle time. The warning counts down. Press the button and the stream continues. Let it run out and the session ends with `endKind: 'afk'`.

> [!TIP]
>
> While you test, shorten the wait: `afk: { timeoutSec: 30 }` in the options. Your code can make the idle time shorter than the project's setting, never longer.

If the viewer watches without clicking, for example during a video inside the application, call `stream.keepAlive()` from your page from time to time. The application can do the same with a `heartbeat` message: see [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md#messages-the-sdk-acts-on-for-you).

## A React hook

Intermediate Creates a stream when a component mounts and removes it when the component unmounts. It is safe under `<StrictMode>` and on fast route changes.

React can run a component's cleanup **before** `create()` has resolved. A cleanup that only calls `stream.destroy()` then has nothing to destroy, and the session that `create()` starts afterwards streams with nobody watching. The `signal` option solves it: abort before `create()` resolves and nothing starts; abort afterwards and the stream is destroyed.

```ts title="use-streampixel.ts" highlight={13,19,29-32} expandable theme={"dark"}
import { useEffect, useRef, useState } from 'react';
import { Streampixel, type StreamState } from '@streampixel/web-sdk';

export function useStreampixel(appId: string) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [stream, setStream] = useState<Streampixel | null>(null);
  const [state, setState] = useState<StreamState | null>(null);
  const [error, setError] = useState<unknown>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    const ac = new AbortController();
    let off: (() => void) | undefined;
    setStream(null);
    setState(null);
    setError(null);

    Streampixel.create({ appId, container, signal: ac.signal })
      .then((s) => {
        setStream(s);
        setState(s.state);            // 'awaitingPassword' already, on a password project
        off = s.on('state', setState);
      })
      .catch((err: unknown) => {
        if ((err as Error)?.name !== 'AbortError') setError(err);
      });

    return () => {
      off?.();     // destroy() announces 'ended' before it drops listeners: stop listening first
      ac.abort();  // before create() resolves: nothing starts. After: the stream is destroyed.
    };
  }, [appId]);

  return { containerRef, stream, state, error };
}
```

```tsx title="Stream.tsx" theme={"dark"}
import { useStreampixel } from './use-streampixel';

export function Stream({ appId }: { appId: string }) {
  const { containerRef, state, error } = useStreampixel(appId);
  const text = error ? 'The stream could not start.'
    : !state ? 'Loading…'
    : state.kind === 'ended' ? state.message
    : state.kind === 'streaming' ? ''
    : state.kind;

  return (
    <div style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9' }}>
      <div ref={containerRef} style={{ width: '100%', height: '100%' }} />
      {text && <p style={{ position: 'absolute', top: 8, left: 8 }}>{text}</p>}
    </div>
  );
}
```

* **Keep the container `<div>` empty in your JSX.** The SDK adds and removes its own child there.
* **Use the returned `stream`** for everything else on this page: `stream?.on(...)` in an effect of your own, `stream?.send(...)` in a click handler.
* **Other frameworks:** the same pattern works wherever a component has a cleanup step. Create on mount, pass a `signal`, abort it on unmount.

## Start on a button press

Beginner Starts the stream only when the viewer asks for it. No session, and so no GPU, is used before the click.

```html title="Add inside #player" theme={"dark"}
<div id="start-screen" class="over">
  <button id="start">Start the experience</button>
</div>
```

```js title="main.js (replaces the one above)" highlight={8,13} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

const container = document.getElementById('stream');
const startScreen = document.getElementById('start-screen');
const startButton = document.getElementById('start');

// Optional warm-up: downloads and checks the engine now. It starts no session.
Streampixel.preload().catch(() => {});   // a failure here is not final: create() tries again

startButton.addEventListener('click', async () => {
  startButton.disabled = true;
  try {
    const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
    startScreen.hidden = true;
    // add your listeners and the other recipes here
  } catch (err) {
    startButton.disabled = false;
    startButton.textContent = 'Could not start. Try again';
    console.error(err);
  }
});
```

> [!TIP]
>
> The page loads with a button and no video. After the click the stream connects. With the warm-up, the engine is already in the browser, so `create()` does not have to download it first.

## A stats readout

Intermediate Shows the viewer, or you, what the stream is doing. The `stats` event fires every second while the video is up.

```html title="Add inside #player" theme={"dark"}
<pre id="stats" class="stats" hidden></pre>
<button id="stats-toggle" style="position: absolute; right: 12px; top: 12px; z-index: 60;">Stats</button>
```

```js title="Add to main.js" theme={"dark"}
const statsBox = document.getElementById('stats');

document.getElementById('stats-toggle').addEventListener('click', () => {
  statsBox.hidden = !statsBox.hidden;
});

stream.on('stats', (s) => {
  if (statsBox.hidden) return;
  statsBox.textContent = [
    `Frame rate  ${s.fps} fps`,
    `Round trip  ${s.latencyMs} ms`,
    `Resolution  ${s.resolution ?? '—'}`,
    `Codec       ${s.codec ?? '—'}`,
    `Bitrate     ${s.bitrateKbps == null ? '—' : (s.bitrateKbps / 1000).toFixed(1) + ' Mbps'}`,
    `Path        ${s.relayTransport ? 'relay over ' + s.relayTransport.toUpperCase() : 'direct'}`,
    `Dropped     ${s.framesDropped} frames`,
    `Lost        ${s.packetsLost ?? '—'} packets`,
  ].join('\n');
});
```

Every field is explained in [`StreamStats`](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states#streamstats). For a deeper look at a bad session, see [Diagnostics](https://docs.streampixel.io/resources/web-sdk-v2/diagnostics.md).

## Saving a screenshot

Beginner Saves the current video frame as a PNG, from your own button and when the application asks.

```html title="Add inside #player" theme={"dark"}
<button id="shot" style="position: absolute; right: 12px; bottom: 12px; z-index: 60;">Save screenshot</button>
```

```js title="Add to main.js" theme={"dark"}
function savePng(dataUrl, fileName) {
  const a = document.createElement('a');
  a.href = dataUrl;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// 1. The viewer presses your button.
document.getElementById('shot').addEventListener('click', () => {
  const dataUrl = stream.captureScreenshot();   // null before the first frame
  if (dataUrl) savePng(dataUrl, `screenshot-${Date.now()}.png`);
});

// 2. The application asks for one, with its requestScreenshot message.
stream.on('screenshot', ({ dataUrl }) => savePng(dataUrl, `from-app-${Date.now()}.png`));
```

The picture is the video frame only. Your own buttons and overlays are not in it. Without the second listener, the SDK saves an application's request as `pixelstream_screenshot.png`.

## Start again after the session ends

Intermediate `ended` is final: a stream cannot be connected again. To start again, destroy it and create a new one.

```html title="Add inside #player" theme={"dark"}
<div id="end" class="over" hidden>
  <div>
    <p id="end-text"></p>
    <button id="again">Start again</button>
  </div>
</div>
```

```js title="main.js (replaces the one above)" highlight={9,12} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

const container = document.getElementById('stream');
const endCard = document.getElementById('end');
let stream;

async function start() {
  endCard.hidden = true;
  stream?.destroy();   // always, before another stream in the same container
  stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
  stream.on('ended', ({ message, endKind }) => {
    if (endKind === 'user') return;   // your own destroy() or disconnect()
    document.getElementById('end-text').textContent = message;   // a sentence for the viewer
    endCard.hidden = false;
  });
}

document.getElementById('again').addEventListener('click', start);
start();
```

> [!WARNING]
>
> `destroy()` on a live stream fires `ended` too, with `endKind: 'user'`. A page that restarts on every `ended` would restart for ever. Check `endKind`, as above.

With `@streampixel/ui`, pass the function instead: `mountUI(stream, { container, onRestart: start })`. Destroy the UI before the stream.

## Pass the page address to your application

Beginner Sends the query parameters of your page's address to the application when it starts, as a share link does.

> [!TIP]
>
> **Coming from Epic's Pixel Streaming library?** Its method names work on the stream object too: `emitUIInteraction()`, `emitConsoleCommand()` and `addResponseEventListener()`. They are the same calls as `send()`, `consoleCommand()` and `on('ueMessage')`. Use whichever you know. See [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md).

```js title="main.js" highlight={4} theme={"dark"}
const stream = await Streampixel.create({
  appId: 'YOUR_PROJECT_ID',
  container,
  launchParams: Object.fromEntries(new URLSearchParams(location.search)),
});
```

> [!TIP]
>
> Open your page as `https://your-site.example/viewer?unit=A-12&lang=fr`. Shortly after the first frame, the application receives one message: `{ "unit": "A-12", "lang": "fr" }`. Every value is a string.

To send something later, when the viewer presses a button, use `stream.send()` or `stream.emitUIInteraction()`: see [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md#send-a-message-to-unreal).

## Link a session to your own user

Advanced Stores the ids of each session with your own user, so that you can find a viewer's session in your Streampixel analytics.

```js title="Add to main.js, directly after create()" theme={"dark"}
stream.on('session', ({ sessionId, streamerId }) => {
  // '/api/stream-sessions' is your own endpoint.
  fetch('/api/stream-sessions', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ sessionId, streamerId }),
  });
});
```

| Fact | Detail |
| - | - |
| When it fires | Once per session, when the session starts to connect: one moment after `create()` resolves, or after the password on a password project. Attach the listener directly after `create()`. |
| More than once | Again, with new ids, when the SDK recovers into a fresh session. Not on a reconnect that keeps the session. |
| If you attach later | Read `stream.currentSessionId` and `stream.currentStreamerId`. |
| What it carries | The two ids. No ticket and no password. |

## More recipes on other pages

> [card] [Sound, resolution, fullscreen](https://docs.streampixel.io/resources/web-sdk-v2/controls-and-input.md)
>
> A sound button, a resolution picker, a fullscreen button, "Click to start", text input for phones.

> [card] [Messages, files and links](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md)
>
> Send when the stream is ready, a Save button for files, a button for links.

> [card] [Your own password form](https://docs.streampixel.io/resources/web-sdk-v2/access.md#password-projects)
>
> The complete form, with lockouts.

> [card] [Voice and text chat](https://docs.streampixel.io/resources/web-sdk-v2/voice-chat.md)
>
> Join the project's chat room from your page.

## Next steps

> [card] [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md)
>
> One level up: what the SDK does when things go wrong, with the real timings.

> [card] [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md)
>
> Every state and event these recipes use, with payloads.

> [card] [Stream API reference](https://docs.streampixel.io/resources/web-sdk-v2/stream-api.md)
>
> Every method and property of the stream object.

> [card] [Options reference](https://docs.streampixel.io/resources/web-sdk-v2/options.md)
>
> Every option of `create()`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.