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

# Shared sessions

> Run one Unreal app for many people with the Streampixel Web SDK: a host page controls the app, viewer pages watch it. Room IDs, page reloads, what differs for viewers, and limits.

Advanced For developers who want several people to watch one running app. After this page you can open a room as the host, let viewers join it, and handle reloads and reconnects on both sides.

A shared session runs **one** instance of your Unreal app for several people. The **host** owns the session and the input. **Viewers** watch the same stream and cannot control it. This is the SDK side of [Meeting rooms](https://docs.streampixel.io/resources/quick-start-guide/meeting-rooms.md).

The app sends its video once, to a shared-session server (Selective forwarding unit: a server that receives one stream and forwards it to every participant.). That server forwards it to the host and to every viewer. Only the host's input reaches the app.

## Start a shared session

**1. The host opens a room**

The host page calls `create()` with `shared: { role: 'host' }`. The SDK asks the platform for a ticket that names the host's room.

```ts host.ts highlight={6,10} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

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

// The room ID. Viewers need it exactly as read here.
const roomId = host.streamerId;
```

> [!TIP]
>
> The host page goes through the usual states and reaches `streaming`. `host.streamerId` has the form `<id>_<projectId>`.

**2. Give the room ID to the viewers**

The SDK does not carry the room ID to other people: that is your page's job. Send it through your own backend, or put it in a link. This is a pattern, not an SDK feature:

```ts host.ts theme={"dark"}
// Continues the host page above. watch.html is your own viewer page.
const link = `${location.origin}/watch.html?room=${encodeURIComponent(roomId)}`;
await navigator.clipboard.writeText(link); // call this from a click handler
```

**3. Each viewer joins the room**

A viewer page calls `create()` with `shared: { role: 'viewer', hostStreamerId }`. `hostStreamerId` is the host's `stream.streamerId`, unchanged.

```ts viewer.ts highlight={8} theme={"dark"}
import { Streampixel } from '@streampixel/web-sdk';

const roomId = new URLSearchParams(location.search).get('room')!;

const viewer = await Streampixel.create({
  appId: 'YOUR_PROJECT_ID',
  container: document.getElementById('stream')!,
  shared: { role: 'viewer', hostStreamerId: roomId },
});
```

> [!TIP]
>
> The viewer sees the same picture as the host. Mouse, keyboard and touch do nothing on the viewer's page.

> [!WARNING]
>
> Pass the room ID exactly as the host page read it. It has the form `<id>_<projectId>`. A bare ID without the project part does not reach the host, and `create()` rejects with a `TypeError` when the ID is missing or has other characters than letters, digits, `_` and `-`.

Both examples leave out the error handling around `create()`. See [Errors and disconnects](https://docs.streampixel.io/resources/web-sdk-v2/errors-and-disconnects.md).

## Options

**shared** `object`

Omit it for a private session of one viewer (the default).

**properties**

**role** `'host' | 'viewer'` *required*

`'host'` opens a room and runs the app. `'viewer'` watches a host's room.

**hostStreamerId** `string`

Required for a viewer: the host's `stream.streamerId`. Not used for a host.

**advanced.streamerId** `string`

Host only, optional: rejoin a room you opened earlier in the same page. Pass the previous `stream.streamerId`. See [Rejoin the previous room](#rejoin-the-previous-room).

Every other option of `create()` works as usual for the host. For a viewer, some are ignored: see [How host and viewer differ](#how-host-and-viewer-differ).

## Rooms and the host role

The host's `stream.streamerId` is the room.

| Topic | Behaviour |
| - | - |
| Who is the host | Whoever opens a room first. The platform returns a key for the room with the host's ticket. The SDK keeps that key for this browser tab only (`sessionStorage`). |
| Room already taken | A second host for the same room is refused: `create()` rejects with `AuthError`, kind `shared-room-taken`. |
| The host's page reloads | The host comes back to the **same room**. The room ID is kept for the tab (`sessionStorage`, per project). The app keeps running and viewers keep watching. |
| A new tab | Opens a new room. `sessionStorage` belongs to one tab. |
| A second `create()` in the same page | Opens a new room. This includes React StrictMode's double effect in development. |
| Browser storage blocked | A new room on every `create()`. |

### Rejoin the previous room

To come back to the previous room on purpose from the same page, for example from a "Start again" button, pass its ID:

```ts highlight={5} theme={"dark"}
const again = await Streampixel.create({
  appId: 'YOUR_PROJECT_ID',
  container,
  shared: { role: 'host' },
  advanced: { streamerId: host.streamerId },
});
```

## How host and viewer differ

| | Host | Viewer |
| - | - | - |
| Input: mouse, keyboard, touch, gamepad | As the options and the project say | Off, whatever the options say |
| Microphone and camera to the app | As the options and the project say | Off. `setMicrophone()` and `setCamera()` resolve to `false`. |
| Idle timeout | Applies | None. A viewer sends no input, so it is never counted down. |
| Messages the SDK sends to the app at start: `isTouchDevice`, the project's startup commands, `launchParams` | Sent | Not sent. One app serves the whole room, and the host sends them. |
| `setResolution()` | Works | Returns `null`. The size of the stream is the host's. |
| `stream.streamerId` | The room ID, `<id>_<projectId>` | `SFU_` followed by the room ID |
| Reconnect window after a drop | 180 seconds | 10 minutes |
| No offer from the platform after signalling connected | Ends with code `4104` after 210 seconds | The SDK sets no limit of its own. The platform decides how long a viewer waits for a host. |

## When things go wrong

A shared session recovers differently from a normal one, because a fresh app would restart the room under everyone.

| What happens | Host | Viewer |
| - | - | - |
| The connection drops | Reconnects as usual, for up to 180 seconds. State `reconnecting`. | Reconnects for up to 10 minutes. State `reconnecting` with `waitingForHost: true`. |
| The host's app stops, or the platform closes the connection for a reason that is not final | The session ends with the platform's code, for example `4006`. | State `reconnecting` with `waitingForHost: true`, for up to 10 minutes. The platform may end a viewer sooner when no host comes back. |
| The video stops | The session **ends** with code `4102`, or `4101` when the video connection never came up. No fresh session is started. | The viewer rejoins the room, up to three times. State `recovering` with `attempt` 1 to 3. After that the session ends with `4102` or `4101`. |
| A final close: access refused, project switched off, no server available, application not found or failed, maximum runtime reached, no streamer connected, relay unavailable | Ends | Ends |

Show a viewer what it is waiting for:

```ts viewer.ts theme={"dark"}
viewer.on('state', (s) => {
  if (s.kind === 'reconnecting' && s.waitingForHost) setStatus('Waiting for the host…');
  else if (s.kind === 'recovering') setStatus(`Rejoining the room (attempt ${s.attempt})…`);
  else if (s.kind === 'streaming') setStatus('');
});
```

The timings behind this table are in [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md).

## Leaving

The host and each viewer end their own page's session with `stream.disconnect()` or `stream.destroy()`.

## Limits

* A shared session cannot be combined with [Test locally](https://docs.streampixel.io/resources/web-sdk-v2/test-locally.md): `dev` together with `shared` is refused with a `TypeError`.
* A room has one host. A second host for the same room is refused with `shared-room-taken`.
* Viewers cannot control the app, cannot change the resolution and cannot send their microphone or camera to the app.
* The host gets no automatic fresh session when the video stops. Offer a "Start again" button on the host page, and [rejoin the previous room](#rejoin-the-previous-room) if you want viewers to stay.
* How hosts and viewers count towards your plan is described in [Meeting rooms](https://docs.streampixel.io/resources/quick-start-guide/meeting-rooms.md#host-vs-guest).

## Chat in a shared session

Voice and text chat work the same for hosts and viewers. See [Voice chat](https://docs.streampixel.io/resources/web-sdk-v2/voice-chat.md).

## Your app only

> [!WARNING]
>
> **Not available yet.** The "Your app only" access setting, and the host key described here, are not released on the platform. This section describes how they will work.

On a project set to [Your app only](https://docs.streampixel.io/resources/web-sdk-v2/access.md#your-app-only) (not available yet), your server requests the tickets, so **your server must ask for the host role itself**. Add an `sfu` field to the body of the ticket request:

| Ticket for | `sfu` in the request body |
| - | - |
| The host, opening a room | `{ "role": "host", "roomId": "<room id>" }` |
| The host again, same room (after a page reload) | `{ "role": "host", "roomId": "<room id>", "hostKey": "<key>" }` |
| A viewer | `{ "role": "viewer" }` |

> [tab] Your server
>
> ```ts ticket-server.ts theme={"dark"}
> // YOUR SERVER: a ticket for the HOST of a shared session.
> export async function requestHostTicket(projectId: string, viewerId: string, roomId: string, hostKey?: 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 ?? '' },
>     body: JSON.stringify({
>       projectId,
>       viewerId,
>       sfu: { role: 'host', roomId, ...(hostKey ? { hostKey } : {}) },
>     }),
>   });
>   if (!res.ok) throw new Error(`Streampixel ticket request failed: ${res.status}`);
>   // The answer carries sfu: { role: 'host', roomId, hostKey }. Keep hostKey on your server for this room:
>   // the next host ticket for the same room (after the host's page reloads) must send it back.
>   return res.json();
> }
> ```

> [tab] Your page
>
> With a ticket function, the SDK tells your page which `sfu` field to forward. `/api/stream-ticket` is your own endpoint.
>
> ```ts host.ts highlight={10} theme={"dark"}
> const host = await Streampixel.create({
>   appId: 'YOUR_PROJECT_ID',
>   container,
>   shared: { role: 'host' },
>   auth: {
>     mode: 'ticket',
>     ticket: ({ sfu }) => fetch('/api/stream-ticket', {
>       method: 'POST',
>       headers: { 'content-type': 'application/json' },
>       body: JSON.stringify({ sfu }), // forward it unchanged in your server's ticket request
>     }).then((res) => res.json()),
>   },
> });
> ```

* The response carries `sfu: { role: 'host', roomId, hostKey }`. The SDK connects as that `roomId`, and `stream.streamerId` is that ID: give it to viewers as `hostStreamerId`.
* Use the form the SDK uses for its own room IDs: `<your room id>_<projectId>`, with letters, digits, `_` and `-` only.
* Every participant needs a ticket of its own: the host, each viewer, and a new one for every `create()`.

## Troubleshooting

> [accordion] Viewers do not see the host's stream
>
> Check the ID the viewer passes as `hostStreamerId`. It must be the host's `stream.streamerId`, unchanged, with the `_<projectId>` part. Check that host and viewer use the same `appId`. Check that the host is `streaming`: a viewer that opens before the host waits.

> [accordion] create() rejects with shared-room-taken
>
> The room already has a host. Another page opened it first, or this page lost the key for the room (a new tab, or blocked browser storage). Open a new room: call `create()` without `advanced.streamerId`.

> [accordion] The host gets a new room on every reload
>
> The room ID is kept in the tab's `sessionStorage`. A new tab starts a new room, and so does a page whose browser storage is blocked, for example inside a third-party frame. A second `create()` in the same page also opens a new room: in React, pass an `AbortSignal` so that StrictMode's first effect starts nothing.

> [accordion] A viewer stays in reconnecting
>
> The viewer is waiting for the host: `waitingForHost` is `true`. It waits for up to 10 minutes, then the session ends with code `4007`. The platform may end it sooner.

> [accordion] The host's session ended with 4102 and the viewers are waiting
>
> The host's video stopped, and a host gets no fresh session. Start the host again. To keep the same room, pass `advanced: { streamerId }` with the previous `stream.streamerId`.

## Next steps

> [card] [Voice chat](https://docs.streampixel.io/resources/web-sdk-v2/voice-chat.md)
>
> Let host and viewers talk and type.

> [card] [Reliability](https://docs.streampixel.io/resources/web-sdk-v2/reliability.md)
>
> One level up: the reconnect windows and what the SDK does when the video stops.

> [card] [Options](https://docs.streampixel.io/resources/web-sdk-v2/options.md)
>
> Reference: `shared`, `advanced.streamerId` and everything else `create()` accepts.

> [card] [Meeting rooms](https://docs.streampixel.io/resources/quick-start-guide/meeting-rooms.md)
>
> The same feature with share links, without code.


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