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

# Access: public, password, single sign-on

> What a Streampixel Web SDK page does for each project access setting: public, password with your own form, single sign-on redirects, and your app only (not available yet).

Advanced For developers who ship a page for a project that is not open to everyone. After this page your page handles a password, a sign-in and their failures without surprising the viewer.

Who may watch a project is set in the dashboard, not in your code: see [Security and access control](https://docs.streampixel.io/resources/quick-start-guide/security-control.md) and [SSO access](https://docs.streampixel.io/resources/quick-start-guide/sso-access.md). Your page follows that setting. With the default `auth` you write no access code for a public project.

| Project access | What `Streampixel.create()` does with the default `auth` | Your code |
| - | - | - |
| Public | Starts the stream. | None. |
| Password | Resolves with the stream in the state `awaitingPassword`. Nothing has started. | A password form, or `@streampixel/ui`. |
| Single sign-on (SSO) | Sends the browser to the sign-in page. Back on your page, the next `create()` finishes the sign-in. | None for the normal path. A message for a refused sign-in. |
| Your app only (not available yet) | Rejects with `AuthError`, kind `server-ticket-required`. | See [the section below](#your-app-only). |

> [!NOTE]
>
> **Moving a page from v1?** Your page follows the project's access setting: check it first, so a password or sign-in screen does not surprise your viewers. See [Migrating from v1](https://docs.streampixel.io/resources/web-sdk-v2/migration.md#before-you-start).

The offline check comes first. A viewer is never asked for a password, or sent to sign in, for a project that cannot stream.

## Which screens are yours

| Screen | When | Who draws it |
| - | - | - |
| Password form | After `create()` resolved, in the state `awaitingPassword` | [`@streampixel/ui`](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays), or your own form (below). |
| "Sign-in failed", "This stream is unavailable" | `create()` rejected, so there is no stream | Always yours. The `AuthError` carries the project's `branding` (logo, banner, loading texts), so your screen can look like the project. |

## Password projects

On a password project `create()` does **not** throw. It resolves, and `stream.state.kind` is `'awaitingPassword'`. No ticket (A short-lived credential for one streaming session. The platform issues it after it has checked the password or the sign-in.) has been requested and no GPU is in use.

> [tab] With @streampixel/ui
>
> Mount the ready-made screens. The password screen is one of them, with the project's logo, the wrong-password message and the lockout countdown.
>
> ```ts title="main.ts" theme={"dark"}
> import { Streampixel } from '@streampixel/web-sdk';
> import { mountUI } from '@streampixel/ui';
>
> const container = document.getElementById('stream')!;
> const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
> const ui = mountUI(stream, { container });
> ```
>
> > [!TIP]
> >
> > Open the page for a password project. You see "This stream is protected", a password field and **Continue**. The right password starts the stream.

> [tab] Your own form
>
> **1. Add a form to your page**
>
> ```html title="index.html" theme={"dark"}
> <div id="stream" style="width: 100%; aspect-ratio: 16 / 9;"></div>
>
> <form id="password-form" hidden>
>   <label for="password">This stream is protected. Enter the password.</label>
>   <input id="password" type="password" autocomplete="off" required />
>   <button id="password-submit">Continue</button>
>   <p id="password-note" role="alert"></p>
> </form>
> ```
>
> **2. Show it in the state awaitingPassword and answer with submitPassword()**
>
> ```js title="password.js" expandable theme={"dark"}
> import { Streampixel } from '@streampixel/web-sdk';
>
> const form = document.getElementById('password-form');
> const field = document.getElementById('password');
> const button = document.getElementById('password-submit');
> const note = document.getElementById('password-note');
> let unlockTimer;
>
> const stream = await Streampixel.create({
>   appId: 'YOUR_PROJECT_ID',
>   container: document.getElementById('stream'),
> });
>
> function render(s) {
>   clearTimeout(unlockTimer);
>   if (s.kind !== 'awaitingPassword') { form.hidden = true; return; }
>
>   form.hidden = false;
>   field.value = '';
>   field.disabled = button.disabled = s.hard === true;   // hard lockout: every attempt is refused for now
>   note.textContent =
>     s.hard ? (s.retryAfterSec ? `Too many attempts. Try again in ${s.retryAfterSec} seconds.` : 'Too many attempts. Please try again later.')
>     : s.locked ? 'Too many incorrect attempts. Check the password and try again.'
>     : s.wrong ? 'Incorrect password. Please try again.'
>     : '';
>
>   // The state does not change by itself when the wait is over: enable the form again.
>   if (s.hard && s.retryAfterSec) {
>     unlockTimer = setTimeout(() => {
>       field.disabled = button.disabled = false;
>       note.textContent = '';
>     }, s.retryAfterSec * 1000);
>   }
> }
>
> stream.on('state', render);
> render(stream.state);   // create() resolves already in 'awaitingPassword'
>
> form.addEventListener('submit', async (e) => {
>   e.preventDefault();
>   button.disabled = true;
>   try {
>     await stream.submitPassword(field.value);   // resolves for a right AND for a wrong password
>   } catch (err) {
>     note.textContent = err.message;             // a network error, or the project went offline
>     button.disabled = false;
>   }
> });
> ```
>
> The file uses `await` at the top level: load it as a module (`<script type="module">`), or through your bundler.
>
> > [!TIP]
> >
> > A wrong password shows "Incorrect password" and the field is empty again. The right password hides the form and the stream connects.

### The `awaitingPassword` state

The state object is `{ kind: 'awaitingPassword' }`, with up to four extra fields. With none of them, the stream is simply waiting for a password: show the field.

**wrong** `boolean`

`true`: the last password was refused. Say so, and let the viewer try again.

**locked** `boolean`

`true`: too many wrong attempts. This is a soft lockout: **the right password is still accepted**, so keep the field usable.

**hard** `boolean`

`true`, together with `locked`: every attempt is refused for now. Disable the form.

**retryAfterSec** `number`

How long the lockout lasts, in seconds, when the server said. The SDK does not change the state when the time is over: use your own timer to enable the form again.

### `submitPassword(password)`

Call it with what the viewer typed. It returns a promise.

| Outcome | The promise | The state |
| - | - | - |
| Right password | Resolves. | `connecting`, then as usual. |
| Wrong password | Resolves. | `awaitingPassword` with `wrong: true`. |
| Too many wrong attempts | Resolves. | `awaitingPassword` with `locked: true`, and `hard: true` when every attempt is refused. |
| Network error, or the project went offline | Rejects with `AuthError`. | Stays `awaitingPassword`. |
| Called in another state, or while a check is running | Rejects with `Error`. | Unchanged. |
| An empty password, or a value that is not a string | Rejects with `TypeError`. | Unchanged. |

> [!WARNING]
>
> A wrong password does **not** reject. Read the result from the state, not from a `catch`.

### Remembering the password

After a correct password the SDK keeps it **for this browser tab only** (`sessionStorage`) and tries it silently on the next `create()`. A page reload does not ask again.

| Fact | Detail |
| - | - |
| Where | `sessionStorage`, under `spx:pw:` and the project id. It is gone when the tab closes, and other tabs do not see it. |
| The remembered password no longer works | The viewer is asked again, without `wrong`: they typed nothing this time. |
| Switch it off | `rememberPassword: false` in the options. |
| What travels | The password travels only in the ticket request, and the server checks it. It is never logged and never sent in telemetry. |

### Ask before you start

If your page asks for the password before it starts the stream, pass it with `auth`:

```js title="A password from your own form" highlight={4} theme={"dark"}
const stream = await Streampixel.create({
  appId: 'YOUR_PROJECT_ID',
  container: document.getElementById('stream'),
  auth: { mode: 'password', password: passwordField.value },
});
```

A wrong one lands in `awaitingPassword` with `wrong: true`, exactly as above. The same form can then retry with `submitPassword()`.

> [!WARNING]
>
> Never write a project password in your page's code. Anyone can read a page's code. Pass only what the viewer typed.

## Single sign-on

With the default `auth` there is nothing to write for the normal path. The SDK does the redirect and finishes the sign-in.

**1. Your page calls create()**

The SDK sends the browser to the sign-in page. Just before the page navigates away, `create()` rejects with `AuthError`, kind `sso-required`. Ignore that one.

**2. The viewer signs in**

The viewer comes back to the same address of your page: origin, path and query string. A `#fragment` is not kept.

**3. Your page loads again and calls create() again**

The address now carries a single-use grant, `?ssoGrant=`. The SDK uses it, removes it from the address bar, and starts the stream.

> [!TIP]
>
> A viewer who is already signed in at your identity provider sees the stream after a short redirect, without typing anything.

Three things to know:

* **Your page's domain must be on the project's allowed domains list.** Single sign-on returns the viewer only to a page on that list. Set it under **Domain restrictions**: see [SSO access](https://docs.streampixel.io/resources/quick-start-guide/sso-access.md).
* **The SDK uses two query parameters**, `ssoGrant` and `ssoError`. It reads them and removes them from the address bar. Do not use these names for parameters of your own.
* **A reload starts the sign-in again.** The grant works once. When the viewer is still signed in at your identity provider, the redirect is usually instant.

### When the sign-in fails

A sign-in that was refused, or a grant that was already used or has expired, rejects `create()` with `AuthError`, kind `sso-failed`.

**err.message** `string`

One of a fixed set of sentences for the viewer, for example "Sign-in was cancelled or refused. Please sign in again." or "Your account is not allowed to open this stream. Ask the project owner for access." Show it.

**err.ssoStartUrl** `string`

Navigate here to start the sign-in again.

**err.ssoErrorCode** `string`

The sign-in service's error code. For your logs, not for the viewer.

```js title="Handle both sign-in errors" highlight={8-13} theme={"dark"}
import { Streampixel, AuthError } from '@streampixel/web-sdk';

try {
  const stream = await Streampixel.create({ appId: 'YOUR_PROJECT_ID', container });
  // ... attach listeners
} catch (err) {
  if (!(err instanceof AuthError)) throw err;
  if (err.kind === 'sso-required') {
    // The browser is already on its way to the sign-in page: show nothing.
  } else if (err.kind === 'sso-failed') {
    showMessage(err.message);
    showSignInButton(() => window.location.assign(err.ssoStartUrl));
  } else {
    showMessage(err.message);
  }
}
```

`showMessage` and `showSignInButton` are your own functions.

> [!WARNING]
>
> On `sso-failed`, show a button. Do not navigate to `ssoStartUrl` by yourself: a viewer whose account is not allowed would go round in a loop.

### Do the redirect yourself

Use `redirect: 'manual'` when your page should decide when to leave: a single-page app with a router, or your own "Sign in" button. The SDK then never navigates.

```js title="Manual redirect" highlight={5} theme={"dark"}
try {
  await Streampixel.create({
    appId: 'YOUR_PROJECT_ID',
    container,
    auth: { mode: 'sso', redirect: 'manual' },
  });
} catch (err) {
  if (!(err instanceof AuthError)) throw err;
  const signInUrl = err.ssoStartUrl;
  if ((err.kind === 'sso-required' || err.kind === 'sso-failed') && signInUrl) {
    if (err.kind === 'sso-failed') showMessage(err.message);
    showSignInButton(() => window.location.assign(signInUrl));
  } else {
    showMessage(err.message);
  }
}
```

After the sign-in, the viewer lands on your page with the grant in the address, and the same `create()` call starts the stream.

## Your app only

> [!WARNING]
>
> **Your app only is not available yet.** Until it is, restrict a project with a password or with single sign-on.

Your app only (not available yet) is the access setting for a site that already signs its own users in. In this mode a stream starts only from a page that passes a ticket requested by **your server**. No password and no Streampixel sign-in is involved.

The SDK's side of it is in the API already:

| In the SDK today | Behaviour |
| - | - |
| A project in this mode, opened without a ticket | `create()` rejects with `AuthError`, kind `server-ticket-required`. |
| `auth: { mode: 'ticket', ticket }` | Accepts the response of your server's ticket request, or a function that returns it. |

> [accordion] How a page passes a ticket (not available yet)
>
> **1. Your server requests a ticket**
>
> Behind your own sign-in check, your server calls `POST https://platform.streampixel.io/api/v1/stream/ticket` with the project's server key in the `x-server-key` header.
>
> ```ts title="server.ts" theme={"dark"}
> // YOUR SERVER (Node 18+). Call it only after your own sign-in check.
> export async function requestStreamTicket(projectId: string, viewerId: string): Promise<unknown> {
>   const res = await fetch('https://platform.streampixel.io/api/v1/stream/ticket', {
>     method: 'POST',
>     headers: {
>       'content-type': 'application/json',
>       'x-server-key': process.env.STREAMPIXEL_SERVER_KEY ?? '', // never in a page
>     },
>     body: JSON.stringify({ projectId, viewerId }), // viewerId: your own id for this user
>   });
>   if (!res.ok) throw new Error(`Streampixel ticket request failed: ${res.status}`);
>   return res.json(); // send this WHOLE object to your page, unchanged
> }
> ```
>
> **2. Your page passes the whole response to the SDK**
>
> Pass a function. The SDK calls it at `create()`, and again when it opens a fresh session by itself.
>
> ```ts title="page.ts" theme={"dark"}
> // '/api/stream-ticket' is your own endpoint. It returns what requestStreamTicket() returned.
> const stream = await Streampixel.create({
>   appId: 'YOUR_PROJECT_ID',
>   container,
>   auth: {
>     mode: 'ticket',
>     ticket: async (ctx) => {
>       // ctx.reason is 'start' or 'recovery'. ctx.sfu is set for a shared session: forward it.
>       const res = await fetch('/api/stream-ticket', {
>         method: 'POST',
>         headers: { 'content-type': 'application/json' },
>         body: JSON.stringify({ sfu: ctx.sfu }),
>       });
>       if (!res.ok) throw new Error(`ticket request failed: ${res.status}`);
>       return res.json(); // the whole response object, or its JSON text
>     },
>   },
> });
> ```

> [accordion] Rules for the ticket (not available yet)
>
> | Rule | Detail |
> | - | - |
> | Pass the whole response | `ticket` must be the response of the ticket request as your server received it: the object, or its JSON text. It carries the ticket, the stream settings and the telemetry and chat tokens. The ticket string alone is refused with `AuthError`, kind `server`: it carries no stream settings. |
> | `appId` is still needed | The SDK looks the project up before it uses your ticket. |
> | One ticket per session | A ticket opens one session. Request a new one for every `create()`, a page reload included. Pass a function, so that the SDK can ask for a new ticket when it starts a fresh session by itself (`ctx.reason` is then `'recovery'`). |
> | Your function fails | `create()` rejects with `AuthError`, kind `ticket-provider-failed` when it threw or rejected, or kind `network` when it gave no answer in 15 seconds. |
> | The server key stays on your server | Anyone can read what is in a page. |
> | Telemetry | Sent only when the response you pass still contains `telemetryToken`. |
> | Shared sessions | The host's ticket must ask for the host role. See [Shared sessions](https://docs.streampixel.io/resources/web-sdk-v2/shared-sessions.md). |

## All `auth` values

Exactly one is active per stream.

**\{ mode: 'auto' }** `default`

Follows the project's access setting, as in the table at the top of this page.

**\{ mode: 'password', password }** `password: string`

The viewer already typed the password into your own form. A wrong one resolves in `awaitingPassword` with `wrong: true`.

**\{ mode: 'sso' }** `redirect?: 'auto' | 'manual'`

The same as `'auto'` on a single sign-on project. With `redirect: 'manual'` the SDK does not navigate: `create()` rejects with kind `sso-required` and `ssoStartUrl`, and your code navigates.

**\{ mode: 'ticket', ticket }** `ticket: object | string | function`

Your app only (not available yet): the whole response of your server's ticket request, or a function that returns it.

An `auth.mode` other than these four, or `mode: 'password'` without a password string, rejects `create()` with a `TypeError` before any network call.

## Troubleshooting

> [accordion] A password screen appeared and I did not expect one
>
> The project's access setting is **Password**. Your page follows the project's setting. Change the setting in the dashboard, or keep it and give your viewers the password.

> [accordion] The console shows AuthError sso-required and then the page leaves
>
> That is the normal start of a sign-in. `create()` rejects just before the browser navigates to the sign-in page. Ignore that error in your `catch`.

> [accordion] After signing in, the page reloads and no stream starts
>
> Check that your page's domain is on the project's allowed domains list (**Domain restrictions**), and that your page calls `create()` again when it loads with `?ssoGrant=` in the address.

> [accordion] My catch block never sees a wrong password
>
> A wrong password is not an error. `create()` and `submitPassword()` both resolve, and the state is `awaitingPassword` with `wrong: true`.

> [accordion] The form stays disabled after a lockout
>
> The SDK does not leave the hard lockout by itself. Start a timer for `retryAfterSec` seconds and enable the form when it fires, as in the example on this page. `@streampixel/ui` does this for you.

> [accordion] create() rejects with rate-limited on a public project
>
> Too many requests came from the viewer's network. `err.retryAfterSec` says how long to wait. See [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md).

## Next steps

> [card] [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md)
>
> Every `AuthError` kind and what to show for it.

> [card] [Ready-made screens](https://docs.streampixel.io/resources/web-sdk-v2/ui-overlays.md)
>
> The password screen that `@streampixel/ui` draws.

> [card] [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md)
>
> One level up: what the SDK does when a session has to be restored.

> [card] [Options reference](https://docs.streampixel.io/resources/web-sdk-v2/options.md)
>
> `auth`, `rememberPassword` and every other option.


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