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

# Errors and disconnects

> Every error Streampixel.create() rejects with, every way a Web SDK session ends, all end codes with the sentence shown to the viewer, and what to send to support.

Advanced For developers who ship a page to production. After this page you can handle every failure before a stream starts, tell why a session ended, show the viewer the right sentence, and collect what support needs.

A stream can fail at two moments. Your page handles them in two places.

| When | What happens | Where you handle it |
| - | - | - |
| **Before the stream starts** | `Streampixel.create()` rejects with an error. Nothing is running. | `try` / `catch` around `create()` |
| **After it started** | The session ends. The `ended` event fires and the state becomes `ended`. | `stream.on('ended', …)` |

> [!NOTE]
>
> A password is neither of the two. On a password project `create()` resolves, and the stream waits in the state `awaitingPassword`. A wrong password comes back as that state with `wrong: true`. See [Access](https://docs.streampixel.io/resources/web-sdk-v2/access.md).

## The short version

This handler covers both moments. The sections below explain every branch.

```ts handle-errors.ts highlight={7,9,13} theme={"dark"}
import { Streampixel, AuthError, EngineLoadError } from '@streampixel/web-sdk';

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

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

  stream.on('ended', ({ code, reason, endKind, message }) => {
    status.textContent = message;              // a sentence for the viewer
    console.log('ended', { code, reason, endKind }); // for your logs and for support
  });
} catch (err) {
  if (err instanceof AuthError) {
    status.textContent = `${err.kind}: ${err.message}`;
  } else if (err instanceof EngineLoadError) {
    status.textContent = `The player could not be loaded (${err.reason}).`;
  } else if ((err as Error).name === 'AbortError') {
    // you aborted `signal`: nothing started
  } else {
    throw err; // TypeError: an option is wrong (the message names it)
  }
}
```

## Errors from `create()`

`create()` rejects with one of four errors.

| Thrown | When | What tells you more |
| - | - | - |
| [`AuthError`](#autherror) | The platform refused, could not be reached, or answered something unusable. | `err.kind` |
| [`EngineLoadError`](#engineloaderror) | The engine (the code that runs the stream) could not be downloaded and verified. | `err.reason` |
| [`TypeError`](#typeerror) | An option is wrong. Thrown before any network call. | `err.message` names the option |
| [`AbortError`](#aborterror) | You aborted the `signal` you passed. Nothing started. | `err.name === 'AbortError'` |

`AuthError` and `EngineLoadError` are exported by `@streampixel/web-sdk`, so `instanceof` works.

A full handler for the kinds a viewer can meet:

```ts create-errors.ts expandable theme={"dark"}
import { Streampixel, AuthError, EngineLoadError } from '@streampixel/web-sdk';

declare function showMessage(text: string): void; // your own UI
declare function showError(text: string): void;   // your own UI

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

try {
  await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
} catch (err) {
  if (err instanceof AuthError) {
    switch (err.kind) {
      case 'project-offline':   showMessage('This stream is unavailable right now.'); break;
      case 'project-not-found': showMessage('This stream does not exist.'); break;
      case 'rate-limited':      showMessage(`Too many attempts. Try again in ${err.retryAfterSec ?? 60} seconds.`); break;
      case 'sso-required':      break; // the page is already navigating to the sign-in page
      case 'sso-failed':        showMessage(err.message); break; // err.ssoStartUrl starts the sign-in again
      case 'network':           showMessage('Could not reach Streampixel. Check your connection.'); break;
      default:                  showError(`${err.kind}: ${err.message}`); // err.status: the HTTP status, when there was one
    }
  } else if (err instanceof EngineLoadError) {
    showError(`The player could not be loaded (${err.reason}).`);
  } else if ((err as Error).name === 'AbortError') {
    // you aborted `signal`: nothing started
  } else {
    throw err; // TypeError: an option is wrong (the message names it)
  }
}
```

> [accordion] How long create() can take before it rejects
>
> | Step | Limit | Retries |
> | - | - | - |
> | Each call to the platform (the project lookup, the ticket request) | 10 seconds for the whole call, retries included | Network errors and `502`, `503`, `504` answers are tried up to three times, with a pause of 0.3 and then 0.6 seconds. Any other answer is final: a `403` or a `429` is the platform's decision and is not retried. |
> | The engine download | See [The engine and updates](https://docs.streampixel.io/resources/web-sdk-v2/engine-and-updates.md#time-limits) | Two hosts, tried in turn. |
>
> Aborting `signal` during a platform call rejects at once. Aborting during the engine download rejects as soon as the download has finished or failed.

### `AuthError`

Every `AuthError` has these properties:

**kind** `string` *required*

The category. Switch on it. The table below lists every kind. A newer engine may add a kind this page does not list yet, so keep a `default` branch.

**message** `string` *required*

A description. For `sso-failed` it is one of a fixed set of sentences written for the viewer. For the other kinds, treat it as text for your logs.

**status** `number`

The HTTP status, when the platform answered.

**branding** `object`

The project's logo, banner, loading texts and theme. Present once the project is known, so your own offline or sign-in screen can look like the project.

**ssoStartUrl** `string`

For `sso-required` and `sso-failed`: navigate here to start the sign-in (again).

**ssoErrorCode** `string`

For `sso-failed`: the sign-in service's error code. For logs only.

**retryAfterSec** `number`

For `rate-limited`: seconds until another attempt is accepted, when the platform said.

**hard** `boolean`

For `rate-limited`: `true` means every attempt from this network is refused for now, not only wrong passwords.

All kinds:

| `kind` | Meaning | Extra fields |
| - | - | - |
| `project-not-found` | No project with this ID, or none bound to this page's domain. | |
| `project-offline` | The project is switched off, or has no active build. This is checked first: a viewer is never asked for a password or sent to sign in for a project that cannot stream. | |
| `sso-required` | The viewer must sign in. Thrown just before the SDK navigates to the sign-in page. With `auth: { mode: 'sso', redirect: 'manual' }` it is thrown instead of navigating: go to `ssoStartUrl` yourself. | `ssoStartUrl` |
| `sso-failed` | The sign-in was refused, or its grant was already used or has expired. | `ssoStartUrl`, `ssoErrorCode` |
| `rate-limited` | Too many requests from this network. | `retryAfterSec`, `hard` |
| `shared-room-taken` | [Shared sessions](https://docs.streampixel.io/resources/web-sdk-v2/shared-sessions.md): this room ID already has a host. | |
| `dev-session-not-found` | [Test locally](https://docs.streampixel.io/resources/web-sdk-v2/test-locally.md#errors): no such dev session, or the session was started for another project than `appId`. | |
| `dev-session-expired` | Test locally: the dev session has expired. Start a new one. | |
| `server-ticket-required` | A "Your app only" project (not available yet) was opened without `auth: { mode: 'ticket' }`. | |
| `ticket-provider-failed` | "Your app only" (not available yet): your own ticket function, passed as `auth.ticket`, threw or rejected. | |
| `network` | The platform could not be reached after the retries, or did not answer within 10 seconds. Also thrown when the page does not run in a browser with WebRTC, and when your own ticket function (not available yet) did not answer within 15 seconds. | |
| `server` | The platform's answer was not JSON, or had no ticket or no stream settings (a proxy or a sign-in page may have answered instead of Streampixel). Also a bad `auth.ticket` (not available yet), and any other refusal. See `message` and `status`. | |
| `programmatic-only` | The platform refused the ticket request with a message that names programmatic access. | |
| `password-required`, `password-wrong` | Not thrown for `auth` `'auto'` or `'password'`: those resolve in the state `awaitingPassword`. | |

> [!NOTE]
>
> `stream.submitPassword()` rejects with the same `AuthError` for failures that are not about the password itself (kind `network`, `project-offline` and so on). A wrong password does not reject: it resolves, and the state is `awaitingPassword` with `wrong: true`.

### `EngineLoadError`

The package you install is a small loader. The engine is downloaded when `create()` runs, from `js.streampixel.io` or its mirror `js-backup.streampixel.io`, and verified. When no verified engine can be loaded, `create()` rejects with `EngineLoadError` and no stream starts: the npm package holds no copy of the engine to fall back to. A failed load is not remembered, so calling `create()` again tries again.

`err.reason` says why. The first group is what you can fix in your page or on the viewer's network:

| `reason` | Usual cause | What to do |
| - | - | - |
| `manifest-unavailable` | Neither host answered: the viewer is offline, a firewall or an ad blocker is in the way, or your page's `connect-src` does not allow the two hosts. | Allow the hosts. See [Content-Security-Policy](https://docs.streampixel.io/resources/web-sdk-v2/installation.md#content-security-policy). |
| `engine-blocked` | The engine script was blocked: the network, your page's `script-src`, or a failed integrity check. | Allow the hosts in `script-src`. |
| `engine-timeout` | The engine script did not load within 8 seconds. | Try again. Check the viewer's connection. |
| `trusted-types` | Your Trusted Types policy refused the engine URL. | Allow the policy name `streampixel-sdk`. |
| `no-webcrypto` | The page is not served over `https` or from `localhost`. | Serve the page over `https`. |
| `no-build` | The pinned `engine.version` does not exist. | Check the version you pinned. |
| `no-channel` | The manifest has no build for this `engine.channel`. | Use `'stable'` or `'beta'`. |
| `needs-newer-loader` | The chosen engine needs a newer `@streampixel/web-sdk`. | Update the package. |

The second group means the list of engine builds (the manifest) failed one of the loader's checks and was refused. Your page cannot fix these. If one repeats, contact support with the `reason`.

| `reason` | The check that failed |
| - | - |
| `signature` | The manifest's signature is missing or wrong. |
| `manifest-malformed` | The answer is not a manifest. |
| `manifest-api` | The manifest is for another version of the loader contract. |
| `manifest-incomplete` | The manifest has no sequence number or no expiry. |
| `manifest-expired` | The manifest has expired. A viewer whose clock is far in the future also gets this. |
| `manifest-too-old` | The manifest is older than this package accepts. |
| `manifest-replayed` | The manifest is older than one this browser has already seen. |
| `engine-register` | The engine script loaded and did not register itself. |
| `error` | Anything else. See `message`. |

How the loader finds, checks and loads the engine is described in [The engine and updates](https://docs.streampixel.io/resources/web-sdk-v2/engine-and-updates.md).

### `TypeError`

Option mistakes are reported before any network call. The message names the option.

| Mistake | Result |
| - | - |
| No options object | `TypeError` |
| An `appId` that is not a project ID | `TypeError` |
| A `container` that is not an element (for example a selector string) | `TypeError` |
| A `shared.role` other than `'host'` or `'viewer'`, or a viewer without a valid `hostStreamerId` | `TypeError` |
| An `advanced.streamerId` with other characters than letters, digits, `_` and `-` | `TypeError` |
| A `dev.sessionId` that is not a dev session ID; `dev` together with `shared` or with `auth: { mode: 'ticket' }`; `dev` without `appId` | `TypeError` |
| A `codec.primary` or `codec.fallback` that is not `AV1`, `H264`, `VP9` or `VP8` | `TypeError` |
| An `auth.mode` other than `'auto'`, `'password'`, `'sso'` or `'ticket'`; `auth.mode: 'password'` without a password string | `TypeError` |
| An `advanced.platformHost` or `advanced.telemetryHost` that is not `https` | `TypeError` |
| An `engine.version` that is not a version | `TypeError` |
| `projectId` instead of `appId` | Accepted as `appId`, with a console warning |
| An option name the SDK does not know | Ignored, with a console warning |

All options are listed in [Options](https://docs.streampixel.io/resources/web-sdk-v2/options.md).

### `AbortError`

When you pass `signal` and abort it before `create()` resolves, `create()` rejects with a `DOMException` named `AbortError`. Nothing is left running: no session, no GPU. Aborting after `create()` resolved destroys the stream instead, and `ended` fires with `endKind: 'user'`.

```ts theme={"dark"}
const ac = new AbortController();
const pending = Streampixel.create({ appId: 'YOUR_PROJECT_ID', container, signal: ac.signal });

ac.abort(); // for example in a React effect's cleanup

try {
  await pending;
} catch (err) {
  if ((err as Error).name !== 'AbortError') throw err;
}
```

## How a session ends

Once a stream exists, every ending arrives the same way: the `ended` event, and the state `ended` with the same fields.

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

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

stream.on('ended', ({ code, reason, endKind, message }) => {
  showMessage(message);                    // for the viewer
  console.log({ code, reason, endKind });  // for you and for support
  if (code === DisconnectCodes.NETWORK_BLOCKED) showNetworkHelp();
});
```

**code** `number` *required*

The end code. The tables below list every code. `DisconnectCodes` exports the names.

**reason** `string` *required*

The server's own text, or the SDK's description. For logs and support, not for viewers.

**endKind** `'user' | 'afk' | 'server' | 'error' | 'network-blocked'` *required*

Who ended the session. See the next table.

**message** `string` *required*

A sentence in plain language for the viewer. It is the same wording as Streampixel's share page.

| `endKind` | When | Codes |
| - | - | - |
| `user` | Your code called `disconnect()` or `destroy()`, or aborted `signal`. | `1000` |
| `afk` | The idle time ran out, or a phone or tablet left the tab in the background for 60 seconds. | `1000` |
| `server` | The platform closed the session: access refused, project switched off, an application error, the maximum runtime, and so on. | The platform's code |
| `error` | The SDK gave up: it could not reconnect, no video arrived, or the stream could not be started. | `4007`, `4101`, `4102`, `4103`, `4104` |
| `network-blocked` | The viewer's network allows neither a direct path nor the relay. | `4100` |

> [!WARNING]
>
> `ended` is final. A stream that ended has no `connect()` or `reconnect()`, and all its listeners are removed after `ended` has fired. To start again, call `destroy()` and then `create()` again. See [Start again](#start-again).

### Codes sent by the platform

| Code | `DisconnectCodes` name | `message` |
| - | - | - |
| `1000` | `CLEAN` | With `endKind: 'user'`: "The stream has ended." With `endKind: 'afk'`: "Disconnected due to inactivity. The session closed after no input for a while.", or "The session closed after a minute in the background." With `endKind: 'server'`: "The stream was disconnected." |
| `1001` | `GOING_AWAY` | "The stream was disconnected (…)." with the server's reason in the brackets. |
| `1008` | `UNAUTHORIZED` | "Access was refused: the stream ticket is invalid or has expired. Start a new session to continue." |
| `4000` | `PROJECT_INACTIVE` | "This stream has been turned off by the project owner." |
| `4001` | `NO_WORKER_AVAILABLE` | "No streaming server is available right now. Please try again in a few minutes." |
| `4002` | `APPLICATION_NOT_FOUND` | "The application could not be found on the streaming server. Please contact the project owner." |
| `4003` | `APPLICATION_ERROR` | "The application reported an error and could not continue. Please try again." |
| `4004` | `MAX_RUNTIME_REACHED` | "The session ended after reaching its maximum allowed runtime." |
| `4005` | `STREAMER_TIMEOUT` | "The application took too long to start. Please try again." |
| `4006` | `STREAMER_DISCONNECTED` | "The application closed unexpectedly. Start a new session to continue." |
| `4008` | `SESSION_SETUP_FAILED` | "The session could not be set up. Please try again." |
| `4009` | `SESSION_TERMINATED_BY_PLATFORM` | "The session has ended. Start a new one to continue." |
| `4010` | `RELAY_UNAVAILABLE` | "The secure relay for this stream is unavailable right now. Please try again in a few minutes." |
| `4401` | `ADMISSION_REQUIRED` | "The stream did not accept this session's access ticket. Start a new session to continue." |

Notes on this table:

* `1005` and `1006` (`ABNORMAL`) are connection drops. They never end a session by themselves: the SDK reconnects, and ends with `4007` when that fails.
* `4010` is also decided by the SDK itself when the project forces the relay and the platform handed out none. The `endKind` is `server` in both cases.
* A [Test locally](https://docs.streampixel.io/resources/web-sdk-v2/test-locally.md) session that expired ends with `1008` and its own sentence: "This dev session has expired or is not valid any more. Start a new one in the dashboard (Test locally)."
* For causes and fixes on the platform side, see [Disconnect codes](https://docs.streampixel.io/resources/quick-start-guide/disconnect-codes.md).

### Codes decided by the SDK in the browser

The platform never sends these. They mean the cause is on the viewer's side of the connection, or between the viewer and the platform. There is nothing to look for in your application's logs.

| Code | `DisconnectCodes` name | Meaning | `message` |
| - | - | - | - |
| `4007` | `RECONNECT_FAILED` | The connection dropped and could not be restored within the reconnect window. | "We could not reconnect to the stream." |
| `4100` | `NETWORK_BLOCKED` | The viewer's network allows neither a direct path nor the relay. | "This network blocks the connection the stream needs. Ask your IT team to allow it, or try another network." |
| `4101` | `MEDIA_CONNECT_FAILED` | Offer and answer were exchanged and the video connection never came up, also after one fresh session. | "The video connection could not be established. A firewall or VPN may be in the way: try another network, or try again." |
| `4102` | `NO_MEDIA` | Connected, and no video frames arrived, also after one fresh session. | "The stream stopped sending video. Please try again." |
| `4103` | `CLIENT_SETUP_FAILED` | The SDK could not build the connection from what the platform sent: no signalling host, an unusable relay list or an unusable offer. | "The stream could not be started in this browser. Please try again." |
| `4104` | `START_TIMEOUT` | Signalling accepted the viewer and then sent no offer and no queue position for 210 seconds. | "The stream did not start in time. Please try again." |

> [!NOTE]
>
> `DisconnectCodes.SESSION_TERMINATED` is a deprecated second name for `4000`. Use `PROJECT_INACTIVE` for `4000` and `SESSION_TERMINATED_BY_PLATFORM` for `4009`.

### What the SDK retries, and what ends the session

| What happened | A normal session, or the host of a shared session | A viewer of a shared session |
| - | - | - |
| A connection drop: close code `1005` or `1006`, the browser going offline, a video path that dies | Retried, for up to 180 seconds | Retried, for up to 10 minutes |
| No video frames | One fresh session, then the session ends. A shared-session host gets no fresh session: the session ends. | Rejoins the room, up to three times |
| `1008`, `4401`, or one of the platform's final reasons: project inactive, no worker available, application not found, application error, maximum runtime reached, no streamer connected, relay unavailable | Ends | Ends |
| Any other close from the platform | Ends with the platform's code | Keeps waiting for the host, for up to 10 minutes |

The exact timings are in [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md). What your page sees while the SDK recovers is in [Events and states](https://docs.streampixel.io/resources/web-sdk-v2/events-and-states.md#reconnection-and-recovery).

## What to show the viewer

The SDK already wrote the sentence: show `message`. Then decide what to offer next to it.

| `endKind` | Show | Offer |
| - | - | - |
| `user` | Nothing. Your own code ended the session. | |
| `afk` | `message` | A "Start again" button. |
| `server` | `message` | A "Start again" button. For `4000` and `4002` a new attempt does not help until the project owner acts: the sentence says so. |
| `error` | `message` | A "Start again" button. |
| `network-blocked` | `message` | A link for the viewer's IT team: [Network requirements](https://docs.streampixel.io/resources/concepts/network-requirements.md). Another network usually works. |

> [!TIP]
>
> `@streampixel/ui` draws this end screen for you, with the sentence and one button. See [Ready-made screens](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays.md).

### Start again

```ts start-again.ts highlight={9,12} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

declare function showEndCard(text: string, onRestart: () => void): void; // your own UI

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

async function start() {
  stream?.destroy(); // removes the old video and listeners
  stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
  stream.on('ended', ({ endKind, message }) => {
    if (endKind === 'user') return; // your own destroy() or disconnect()
    showEndCard(message, start);
  });
}

start();
```

`destroy()` on a live stream fires `ended` with code `1000` and `endKind: 'user'` before it drops the listeners. That is why the listener returns early for `user`: without the check, a restart would show an end card for the stream you just replaced. This example leaves out the `try` / `catch` around `create()` shown in [The short version](#the-short-version).

## What to send to support

Collect these four things. The first three are available at any time after `create()` resolved.

**1. The session's IDs**

`stream.currentSessionId` and `stream.currentStreamerId`. They are the IDs in your Streampixel analytics. The `session` event announces them, also when the SDK moves to a fresh session.

**2. The engine version**

`stream.engineVersion`. The engine updates by itself, so it can differ from the package version you installed.

**3. The end**

The `ended` payload: `code`, `reason` and `endKind`.

**4. A connection snapshot**

`await stream.getDiagnostics()`, taken **while the stream is still up**. After the end it returns `null`. The `stalled` event carries the same kind of snapshot at the moment the video stopped.

```ts support-report.ts theme={"dark"}
import type { Streampixel } from '@streampixel/web-sdk';

export function collectSupportReport(stream: Streampixel) {
  const report: Record<string, unknown> = {
    engineVersion: stream.engineVersion,
    session: { sessionId: stream.currentSessionId, streamerId: stream.currentStreamerId },
  };

  stream.on('session', (ids) => { report.session = ids; }); // new IDs when the SDK moves to a fresh session
  stream.on('stalled', (diagnostics) => { report.stalled = diagnostics; });
  stream.on('ended', ({ code, reason, endKind }) => {
    report.ended = { code, reason, endKind };
    console.log('Streampixel support report', JSON.stringify(report));
  });

  return report;
}
```

> [!WARNING]
>
> A snapshot from `getDiagnostics()` holds the viewer's network addresses. Send it to support, do not publish it. See [Diagnostics](https://docs.streampixel.io/resources/web-sdk-v2/diagnostics.md).

Send the report to [support@streampixel.io](mailto:support@streampixel.io).

## Common questions

> [accordion] My ended listener fires when I call destroy()
>
> That is expected. `destroy()` ends a live session, so `ended` fires with code `1000` and `endKind: 'user'`, and then the listeners are dropped. Check `endKind`, or unsubscribe before you call `destroy()`. `stream.on()` returns the function that unsubscribes.

> [accordion] The code is 1000 and endKind is server
>
> The platform closed the session cleanly. Your page did not end it: `disconnect()` and `destroy()` give `endKind: 'user'`. The `message` is "The stream was disconnected."

> [accordion] create() rejected, and I see no ended event
>
> `ended` belongs to a stream object, and a rejected `create()` returned none. Handle the error in the `catch`.

> [accordion] The session ended with 4102 although the viewer's network is fine
>
> `4102` means the connection was up and no video frames arrived, also after the SDK tried one fresh session. The usual cause is the application: it stopped rendering or hung. Look at the application, not at the viewer's network. `4101` is the code for a video connection that never came up.

> [accordion] A viewer on an office network gets 4100
>
> The network allows neither a direct path nor the relay. Show the sentence, and point the viewer's IT team to [Network requirements](https://docs.streampixel.io/resources/concepts/network-requirements.md).

## Next steps

> [card] [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md)
>
> One level up: what the SDK does for each failure, with the exact timings.

> [card] [Diagnostics](https://docs.streampixel.io/resources/web-sdk-v2/diagnostics.md)
>
> Read `stats` and `getDiagnostics()`, and debug a bad session.

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

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


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