> ## 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.

# Quick start

> Build a real page with the Streampixel Web SDK from npm: a sized container, create(), the ready-made screens, reacting to state, error handling and cleanup. With a plain TypeScript version and a React version.

Intermediate For web developers who use npm. After this page you have a page that starts your stream, shows the right screen for every situation, reacts to what the stream does, and cleans up after itself.

> [!NOTE]
>
> No build step? [Your first stream](https://docs.streampixel.io/resources/web-sdk-v2/first-stream.md) does the same in one HTML file with a script tag.

## Before you start

| You need | Where |
| - | - |
| A Streampixel project with an active build, and its project ID | [Finding your user and project IDs](https://docs.streampixel.io/resources/api-reference/finding-your-user-and-project-ids.md) |
| A project with a bundler, served over `https` or from `localhost` | [Installation](https://docs.streampixel.io/resources/web-sdk-v2/installation.md) |

No build yet? You can run your page against Unreal on your own machine: see [Test locally](https://docs.streampixel.io/resources/web-sdk-v2/test-locally.md).

## Build the page

**1. Install the two packages**

The SDK:

```bash npm theme={"dark"} theme={"dark"}
npm install @streampixel/web-sdk
```

```bash yarn theme={"dark"} theme={"dark"}
yarn add @streampixel/web-sdk
```

```bash pnpm theme={"dark"} theme={"dark"}
pnpm add @streampixel/web-sdk
```

The ready-made screens:

```bash npm theme={"dark"}
npm install @streampixel/ui
```

```bash yarn theme={"dark"}
yarn add @streampixel/ui
```

```bash pnpm theme={"dark"}
pnpm add @streampixel/ui
```

> [!TIP]
>
> Your `package.json` lists `@streampixel/web-sdk` and `@streampixel/ui`.

**2. Give the video a box**

The SDK puts the video inside an element of your page, the container. Give it a width and a height.

```html index.html theme={"dark"}
<div id="stream" style="width: 100%; height: 100vh"></div>
```

The size is yours to choose: the full window, a 16:9 box in an article, a panel next to a form. See [The container](#the-container) for the rules.

**3. Create the stream and mount the screens**

```ts main.ts highlight={7,8} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';
import { mountUI } from '@streampixel/ui';

const container = document.getElementById('stream')!;

async function start() {
  const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
  const ui = mountUI(stream, { container });

  // the next two steps add code here
}

start();
```

`Streampixel.create()` starts the stream. `mountUI()` draws everything a viewer needs around the video: the loading screen, the password form, "Click to start", the idle warning, the end message and more.

> [!TIP]
>
> Run your dev server and open the page. You see your project's loading screen, then your app. A control bar at the bottom right has sound, stream information and fullscreen.

**4. React to what the stream does**

The stream is always in one state. Listen to `state` for your own logic: analytics, a "live" badge, showing your own controls. Add this inside `start()`, after `mountUI()`.

```ts main.ts theme={"dark"}
stream.on('state', (state) => {
  document.body.classList.toggle('is-live', state.kind === 'streaming');
});

stream.on('ended', ({ code, endKind, message }) => {
  console.log('ended', code, endKind, message); // message is a sentence for the viewer
});
```

Attach your listeners right after `await Streampixel.create(...)`: connecting starts one moment later, so you see every state. All states and events are in [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md).

**5. Talk to your Unreal app**

Send a message once the video is up, and listen for what your app sends back. This also goes inside `start()`.

```ts main.ts theme={"dark"}
stream.on('state', (state) => {
  if (state.kind === 'streaming') {
    const sent = stream.send({ action: 'teleport', to: 'lobby' }); // false = not sent
  }
});

stream.on('ueMessage', (message) => console.log('from Unreal:', message));
```

`send()` returns `false` when the message was not sent: before the video is up, while reconnecting, after the end. Nothing is queued. The state `streaming` can come again after a reconnect, so send only what is safe to repeat. For data your app needs once at its start, use the [`launchParams`](https://docs.streampixel.io/resources/web-sdk-v2/options) option.

> [!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).

**6. Clean up**

When the stream should go away (a closed dialog, a route change), destroy the screens first, then the stream.

```ts main.ts theme={"dark"}
ui.destroy();
stream.destroy();
```

`stream.destroy()` ends the session if it is still live, removes the video and drops every listener. It is safe to call more than once. Keep `stream` and `ui` where your teardown code can reach them: the complete page below keeps both in variables outside `start()`.

## The complete page

The steps above, with error handling and a "Start again" button. Pick your version.

> [tab] Plain TypeScript
>
> **my-site**
>
> **index.html**
>
> **src**
>
> **main.ts**
>
> **package.json**
>
> This is the layout of a Vite project. Any bundler that resolves npm packages works.
>
> ```ts src/main.ts lines theme={"dark"}
> import { Streampixel, AuthError, EngineLoadError } from '@streampixel/web-sdk';
> import { mountUI, type MountedUI } from '@streampixel/ui';
>
> const container = document.getElementById('stream')!;
> const notice = document.getElementById('notice')!;
>
> let stream: Streampixel | undefined;
> let ui: MountedUI | undefined;
>
> async function start() {
>   // Starting again: remove the old screens first, then the old stream.
>   ui?.destroy();
>   stream?.destroy();
>   notice.hidden = true;
>
>   try {
>     const s = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
>     stream = s;
>
>     // The ready-made screens: loading, password, "Click to start", idle warning, end message and more.
>     ui = mountUI(s, { container, onRestart: start });
>
>     // Your own logic, next to them.
>     s.on('state', (state) => {
>       document.body.classList.toggle('is-live', state.kind === 'streaming');
>     });
>     s.on('ueMessage', (message) => console.log('from Unreal:', message));
>     s.on('ended', ({ code, endKind, message }) => console.log('ended', code, endKind, message));
>   } catch (err) {
>     showStartError(err);
>   }
> }
>
> // create() rejected: there is no stream, so the ready-made screens cannot show this one. It is yours to draw.
> function showStartError(err: unknown) {
>   if (err instanceof AuthError && err.kind === 'sso-required') return; // the browser is going to the sign-in page
>
>   let text = 'The stream could not start.';
>   if (err instanceof AuthError) {
>     if (err.kind === 'project-offline') text = 'This stream is unavailable right now.';
>     if (err.kind === 'project-not-found') text = 'This stream does not exist.';
>     if (err.kind === 'network') text = 'Could not reach Streampixel. Check your connection.';
>   } else if (err instanceof EngineLoadError) {
>     text = `The player could not be loaded (${err.reason}).`;
>   }
>   console.error(err); // a TypeError here means an option is wrong: its message names the option
>   notice.textContent = text;
>   notice.hidden = false;
> }
>
> start();
> ```
>
> ```html index.html lines 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>
>       html, body { margin: 0; height: 100%; background: #000; }
>       #stream { width: 100%; height: 100%; }
>       #notice {
>         position: fixed; inset: 0; margin: 0;
>         display: grid; place-items: center;
>         color: #fff; font: 16px system-ui, sans-serif;
>       }
>       #notice[hidden] { display: none; }
>     </style>
>   </head>
>   <body>
>     <div id="stream"></div>
>     <p id="notice" hidden></p>
>     <script type="module" src="./src/main.ts"></script>
>   </body>
> </html>
> ```
>
> What it adds to the steps:
>
> | Part | Why |
> | - | - |
> | `start()` | One function starts the stream, and starts it again. It is passed to `mountUI` as `onRestart`, so the end message's button reads "Start again" and calls it. |
> | `try` / `catch` | `create()` rejects when the stream cannot start. No stream exists then, so the ready-made screens have nothing to attach to: this message is yours to draw. |
> | `sso-required` | On a single sign-on project the SDK sends the browser to the sign-in page, and `create()` rejects with this kind just before the page leaves. Ignore it. |

> [tab] React
>
> ```tsx StreamView.tsx lines theme={"dark"}
> import { useEffect, useRef, useState } from 'react';
> import { Streampixel, AuthError, EngineLoadError } from '@streampixel/web-sdk';
> import { mountUI, type MountedUI } from '@streampixel/ui';
>
> export function StreamView({ appId }: { appId: string }) {
>   const containerRef = useRef<HTMLDivElement>(null);
>   const [run, setRun] = useState(0); // change it to start a new stream
>   const [startError, setStartError] = useState<string | null>(null);
>
>   useEffect(() => {
>     const container = containerRef.current;
>     if (!container) return;
>     const ac = new AbortController();
>     let ui: MountedUI | undefined;
>     setStartError(null);
>
>     Streampixel.create({ appId, container, signal: ac.signal })
>       .then((stream) => {
>         if (ac.signal.aborted) return;
>         ui = mountUI(stream, { container, onRestart: () => setRun((n) => n + 1) });
>         stream.on('ueMessage', (message) => console.log('from Unreal:', message));
>       })
>       .catch((err: unknown) => {
>         if ((err as Error)?.name === 'AbortError') return; // the cleanup ran first: nothing started
>         if (err instanceof AuthError && err.kind === 'sso-required') return; // going to the sign-in page
>         console.error(err);
>         setStartError(
>           err instanceof EngineLoadError ? `The player could not be loaded (${err.reason}).`
>           : err instanceof AuthError && err.kind === 'project-offline' ? 'This stream is unavailable right now.'
>           : 'The stream could not start.'
>         );
>       });
>
>     return () => {
>       ui?.destroy(); // the screens first
>       ac.abort();    // then the stream. Before create() resolves: nothing starts. After: the stream is destroyed.
>     };
>   }, [appId, run]);
>
>   return (
>     <div style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9', background: '#000' }}>
>       {/* Keep this element empty: the SDK and the screens add their own children. */}
>       <div ref={containerRef} style={{ width: '100%', height: '100%' }} />
>       {startError && (
>         <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', color: '#fff' }}>
>           <p>{startError}</p>
>           <button onClick={() => setRun((n) => n + 1)}>Try again</button>
>         </div>
>       )}
>     </div>
>   );
> }
> ```
>
> ```tsx App.tsx theme={"dark"}
> <StreamView appId="YOUR_PROJECT_ID" />
> ```
>
> What to notice:
>
> | Part | Why |
> | - | - |
> | `signal: ac.signal` and `ac.abort()` | The cleanup can run before `create()` has resolved. Aborting the signal then cancels `create()`, and nothing starts. See [React](#react). |
> | `if (ac.signal.aborted) return` | The component went away between `create()` resolving and this line. Mount nothing. |
> | `ui?.destroy()` before `ac.abort()` | The screens first, then the stream. |
> | `run` | Changing it re-runs the effect: the old stream is destroyed and a new one is created. It is how "Start again" and "Try again" work. |
> | The empty `div` | React must not render children into the container: the SDK and the screens add their own. |
>
> The [example app](https://github.com/infinity-void-metaverse/Streampixel-SDK-Example) is a complete React integration that draws its own screens instead of using `@streampixel/ui`.

## What `create()` does

`create()` does four things before it resolves:

1. Downloads and verifies the engine, the code that runs the stream.
2. Looks the project up on the Streampixel platform: is it online, and how do viewers get in.
3. Asks the platform for a ticket, a short-lived credential for one session. A password or single sign-on is checked here.
4. Resolves with the `stream` object. Connecting starts one moment later.

On a password-protected project, `create()` resolves before step 3, with the stream in the state `awaitingPassword`. Nothing has started yet. `@streampixel/ui` shows the password form. See [Access](https://docs.streampixel.io/resources/web-sdk-v2/access.md).

[How it works](https://docs.streampixel.io/resources/web-sdk-v2/how-it-works.md) follows these steps one by one.

### When `create()` rejects

| Thrown | When |
| - | - |
| `AuthError` | The platform refused, could not be reached, or answered something unusable. `err.kind` says which. |
| `EngineLoadError` | The engine could not be loaded. `err.reason` says why. |
| `TypeError` | An option is wrong. The message names it. |
| An error named `AbortError` | You aborted the `signal`. Nothing started. |

Every kind and reason is listed in [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md).

## The container

`container` must be an element, not a selector string. The SDK adds one element of its own to it and puts the video inside.

| Rule | Detail |
| - | - |
| Width | The container needs a width. |
| Height | Give the container a height and the video fills it. If it has a width and no height when the stream starts, the video area takes the stream's aspect ratio instead. |
| CSS `position` | Any. The video fills the container whether it is `static`, `relative` or anything else. `@streampixel/ui` sets `position: relative` on the container when it is `static`. |
| No container | Leave `container` out to start without a video on the page, and call `stream.attach(element)` later. That element needs a height of its own. |
| The `<video>` element | Do not keep a reference to it: the SDK replaces it when it rebuilds the connection. |

> [accordion] How the video is fitted: fixed, dynamic and crop
>
> How the video is fitted depends on the project's [resolution mode](https://docs.streampixel.io/resources/quick-start-guide/resolution-settings.md) in the dashboard, or on the `resolution.mode` option.
>
> | Mode | Stream size | In the container |
> | - | - | - |
> | `fixed` | The start resolution, or the size last set with `setResolution()`. | The whole picture, letterboxed. |
> | `dynamic` | The container's size in device pixels (CSS size × `devicePixelRatio`), never above the start resolution. It follows the container when the container or the window is resized. | Fills the container. |
> | `crop` | Same sizing as `dynamic`. | Fills the container edge to edge. What does not fit is cropped. |
>
> For `dynamic` and `crop`, give the container both a width and a height: a container that has no size yet is measured as the browser window.

## React

React needs one thing done right: cancelling.

* In development under `<StrictMode>`, React runs an effect, its cleanup, and the effect again when a component mounts.
* In production, a fast route change unmounts a component just after it mounted.

In both cases the cleanup runs before `create()` has resolved. A cleanup that only calls `stream.destroy()` has no stream to destroy yet, and that `create()` then resolves into a session that nobody holds: a GPU session that streams unseen.

Pass an `AbortSignal` and abort it in the cleanup. Aborting before `create()` resolves rejects it with an `AbortError` and starts nothing. Aborting later destroys the stream.

> [!WARNING]
>
> Without `signal`, React's StrictMode starts two sessions in development, and a quick route change in production can leave one running.

If you draw your own screens instead of mounting `@streampixel/ui`, this hook gives your components the stream and its state:

```ts useStreampixel.ts lines 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 Stream.tsx theme={"dark"}
import { useStreampixel } from './useStreampixel';

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>
  );
}
```

The cleanup unsubscribes before it aborts: `destroy()` announces `ended` before it drops the listeners, and a state update on a component that is going away is not wanted. A fuller hook is in the [Cookbook](https://docs.streampixel.io/resources/web-sdk-v2/cookbook.md).

## Starting again

A session that has ended cannot be restarted: `ended` is final, and it removes every listener. There is no `connect()` or `reconnect()` on a stream. To start again (a retry button, a route change), destroy the old stream and create a new one.

```ts theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';
import { mountUI, type MountedUI } from '@streampixel/ui';

const container = document.getElementById('stream')!;
let stream: Streampixel | undefined;
let ui: MountedUI | undefined;

async function start() {
  ui?.destroy();       // the screens first, then the stream
  stream?.destroy();
  stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
  ui = mountUI(stream, { container, onRestart: start }); // "Start again" on the end message
}
start();
```

> [!NOTE]
>
> `destroy()` on a live stream fires `ended` (code `1000`, `endKind: 'user'`) before it drops the listeners. If your code starts a new stream when `ended` fires, check `endKind` first, or unsubscribe before you destroy.

## Without the ready-made screens

`@streampixel/ui` is optional. Without it, the SDK draws the video and nothing else, and your page must give the viewer:

| The viewer needs | Built from |
| - | - |
| A loading and queue display | the states `connecting`, `queued`, `reconnecting`, `recovering`; the `progress` and `queue` events |
| A password form, on password projects | the state `awaitingPassword`; `stream.submitPassword()` |
| A "Click to start" button | the state `awaitingPlay`; `stream.play()` |
| A sound button | `stream.toggleAudio()`: streams start muted |
| An idle warning | the `afkWarning` event; `stream.keepAlive()` |
| A text field on phones | the `osk` and `oskHide` events; `stream.sendTextboxEntry()` |
| Save and Open buttons on phones and tablets, for files and links your app sends | the `file` and `openUrl` events |
| An end message | the `ended` event |

[Your first stream](https://docs.streampixel.io/resources/web-sdk-v2/first-stream.md) is a small page that does this by hand. The [Cookbook](https://docs.streampixel.io/resources/web-sdk-v2/cookbook.md) has a recipe for each piece. You can also keep most of the ready-made screens and [replace one](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays.md#replace-one-screen-with-your-own).

## Next steps

> [card] [Ready-made screens](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays.md)
>
> What each screen shows, and how to switch off, restyle or replace one.

> [card] [Talk to your Unreal app](https://docs.streampixel.io/resources/web-sdk-v2/messaging.md)
>
> Messages, console commands, launch parameters, files and links.

> [card] [Controls and input](https://docs.streampixel.io/resources/web-sdk-v2/controls-and-input.md)
>
> Sound, resolution, fullscreen, mouse, keyboard, touch.

> [card] [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md)
>
> One level up: build your own screens on the state machine.


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