# Multiplayer and invites

This guide shows how to connect your game's rooms to the portal's social layer: announcing a room, producing invite links, handling friends' invites and testing it all with two browser tabs. The portal's social layer (rooms, friends, invites) is what this guide covers. Since SDK 1.3.0 the portal can also carry small gameplay messages and a shared state between the players of a room (see [the room data channel](#6-exchange-game-data-in-the-room)); bigger or authoritative traffic stays on your own servers. Signed-in players see an **Invite friends** tray under the game that lists their friends with an Invite button, plus a **Copy invite link** button. Your game tells the portal which room the player is in, and the portal turns that into an invite.

The requirements are on the [multiplayer page](https://docs.zokogames.com/requirements/multiplayer); the method reference is in the [game module](https://docs.zokogames.com/sdk/game#rooms-and-invites). This guide is the order to do it in. Examples assume `const SDK = window.ZokoGames.SDK;` and `await SDK.init();` as in the [SDK introduction](https://docs.zokogames.com/sdk/introduction#loading); unfamiliar terms are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

## How the pieces fit

| Piece | What it does |
| --- | --- |
| `updateRoom({ roomId, isJoinable, inviteParams })` | Tells the portal "this player is in this room". While `isJoinable` is true the **Invite friends** button shows under the game. |
| Invite (friend list) | The host presses Invite on a friend. See [the friend invite flow](#the-friend-invite-flow). |
| `inviteLink(params)` | The game page's URL with your parameters added as query parameters. Players paste it anywhere. |
| `inviteParams` / `getInviteParam(key)` | Every query parameter the game page was opened with, as strings. Read them at start. |
| `addJoinRoomListener(fn)` | Fires when an invite is accepted **while your game is already open**, so you can move the player into the room without a reload. |
| `isInstantMultiplayer` | `true` when the page was opened with `instantJoin=true` ("play together"): skip the menu and go straight to a lobby. The old name `isInstantJoin` still works. |

`showInviteButton(params)` and `hideInviteButton()` are deprecated aliases of `updateRoom({ isJoinable: true, inviteParams })` and `updateRoom({ isJoinable: false })`. New code should call `updateRoom`. They stay because the portal's button follows the room, which a game without rooms cannot use. From SDK 1.7.0 the same two methods take `{ portalOnly: true }`: `showInviteButton(params, { portalOnly: true })` shows the portal's **Invite friends** button with `params` in the link it shares and resolves that link, `hideInviteButton({ portalOnly: true })` hides it again, and neither creates a room or changes `isJoinable`. The `params` follow the same rules as `inviteLink` (a flat object of strings; the page that opens the link keeps a parameter only within the limits listed above). The ask resets when the game reloads, and an `updateRoom` that sets `isJoinable` hands the button back to the room. There is no button in kids mode.

Rooms and presence need a signed-in player. For guests, `updateRoom` succeeds and nothing is announced. A guest with a joinable room can still share the link directly from the button; a guest without one is asked to sign in.

## The friend invite flow

1. Your game calls `updateRoom` with `isJoinable: true`. The **Invite friends** button appears under the game for multiplayer games and whenever a room is joinable.
2. A signed-in host opens the tray, which lists friends, and presses **Invite** on one. The tray also has a copy-link button.
3. The invite is delivered live to the friend, and a copy is stored so it is still in their notifications later. The friend sees a toast, "{name} invited you to play {game}.", with an **Accept** button, for 15 seconds. Accepting from the toast or from the notification list is the same action.
4. If the friend is **not** in your game, accepting opens the game page with the invite parameters in the address, and your game reads them at start. If they are **already on the game's page**, nothing reloads: your `addJoinRoomListener` callback receives the parameters.
5. The friend needs notifications for invites switched on to see the live toast; the stored notification is kept either way.

Limits worth knowing: only friends can be invited; a host can send 20 invites per hour; a second invite to the same friend for the same game within 2 minutes is treated as a duplicate and not sent again; blocked players and banned accounts cannot be invited.

### What arrives in the parameters

The parameters are the ones you passed in `inviteParams`, plus `roomId`, which the portal always adds (generating one if you omitted it). The same set is in the address as query parameters and in `SDK.game.inviteParams`.

- At most 16 parameters; keys of 1 to 40 letters, digits, `_`, `.` or `-`; values are strings up to 200 characters. The keys `__proto__`, `constructor` and `prototype` are not allowed.
- `roomId` is 1 to 64 letters, digits, `_`, `.` or `-`.
- `inviteParams` returns **every** query parameter on the page address, so it also contains things such as `instantJoin`, `utm_*` or parameters you did not set. Read only the keys you expect and validate them.
- It is `null` when the address has no query string.
- The parameters you pass to `updateRoom` are checked by the portal against the limits above. If one key or value breaks them, **all of your `inviteParams` are dropped silently** (the room is still announced with only `roomId`), and the call does not reject. Keep them short and flat. Keep parameters small, such as a room code or a level id, and test them in the Preview tool before you publish.
- In the portal the address is the **portal page's** address (`/game/<slug>?room=abc`), which the portal passes through to your game; your own game page's address is not used.

The portal limits above apply to what your game sends. The page that hosts your game then filters the query string once more, with one rule, before it fills `inviteParams`: a parameter is kept when its key has 1 to 64 characters from `A-Z a-z 0-9 _ . -` (it may start with a digit or `_`) and its value is any text of up to 256 characters without control characters. At most 30 different keys are kept, and when a key repeats, the last value wins. Only the kinds of parameter in the table are dropped, each on its own; the rest still arrive. The names `roomId`, `instantJoin`, `ref`, `useLocalSdk`, `sdk_debug`, `utm_*` are always accepted as key names, but their values are still checked.

| What | Result | Why |
| --- | --- | --- |
| Every other key and value: values with `/`, `=`, `?`, `%`, spaces or non-Latin letters, and keys that start with a digit or `_` | Kept | These are ordinary game data (a room, a mode, a level, a map link). |
| A key named like a secret or a navigation target of the portal: `token`, `access_token`, `id_token`, `refresh_token`, `jwt`, `bearer`, `csrf`, `otp`, `password`, `pass`, `pwd`, `secret`, `sig`, `signature`, `session`, `auth`, `reset`, `verify`, `verification`, `magic`, `email`, `mail`, `next`, `return`, `returnTo`, `redirect`, `redirect_uri`, `callback`, `callbackUrl`, `apikey`, `ticket`, `nonce`, and `code`, `key`, `state` when they are the whole key. Matching ignores case and also finds the word inside a longer key (`reset_token`, `authCode`, `magicLink`). A key that also has a game word (`room`, `game`, `level`, `map`, `mode`, `lobby`, `match`, `team`, `invite`, `player`, `seed`) is kept: `roomCode`, `roomHash`, `gameState`, `inviteKey` pass. | Dropped | A sign-in, verification or reset token, a one-time code, an email address or a redirect target in a portal address must never reach a game. |
| A value shaped like a JWT, or containing 64 or more unbroken letters, digits or `+`, `/`, `_`, `=`, `-` | Dropped | It looks like a credential, whatever the key is called. |
| A key with other characters or more than 64 characters, a value of more than 256 characters or with a control character, and every key after the 30th | Dropped | It is not valid invite data, or there are too many of them. |

Example 1: a link whose parameters all pass.

```text
/game/my-game?room=abc&mode=ranked&level=12&name=Zo%C3%AB%20%C3%9Cnal
-> { room: "abc", mode: "ranked", level: "12", name: "Zoë Ünal" }
```

Example 2: `token=` is dropped, `roomCode=` is kept.

```text
/game/my-game?token=abc123&roomCode=ABCD&mode=ranked
-> { roomCode: "ABCD", mode: "ranked" }
```

Put secrets in your own backend, never in an invite link.

## 1. Join from the page address

```js
await SDK.init();

const roomFromLink = SDK.game.getInviteParam("room");
if (SDK.game.isInstantMultiplayer) startMatchmaking();
else if (roomFromLink) joinRoom(roomFromLink);
else showMenu();
```

## 2. Announce the room you host

Create your room on your server, then tell the portal. Use the same id you will put in the link.

```js
async function hostRoom() {
  const room = await myServer.createRoom({ max: 4 });              // your own backend
  await SDK.game.updateRoom({
    roomId: room.id,                                               // letters, digits, _ . - (64 characters max; anything else is replaced by _)
    isJoinable: true,
    inviteParams: { room: room.id },                               // flat map of strings only
  });
  copyBtn.onclick = async () => navigator.clipboard.writeText(await SDK.game.inviteLink({ room: room.id }));
}
```

If you omit `roomId`, the portal generates one and always adds it to `inviteParams` as `roomId`. The portal shows the room's capacity as the game's maximum lobby size, capped at 100.

## 3. Update and leave

```js
await SDK.game.updateRoom({ isJoinable: false });                  // room full or round started
await SDK.game.leftRoom();                                          // the player left the room
```

Call `updateRoom` again when the room changes, and `leftRoom` on exit, disconnect and when the game goes back to the menu.

## 4. Handle invites accepted mid-game

```js
SDK.game.addJoinRoomListener(async (params) => {
  if (currentRoom) await leaveCurrentRoom();
  await joinRoom(params.room);
});
```

## 5. Respect chat settings

```js
const apply = (s) => { chatPanel.hidden = s.disableChat; };
apply(SDK.game.settings);
SDK.game.addSettingsChangeListener(apply);
```

Chat needs moderation (a profanity filter and a report option) and must never render raw HTML from other players.

## 6. Exchange game data in the room

Once the player is in a room you can send messages to the other members with `SDK.game.room.send(data, { to })`, receive them with `onMessage`, and keep a small host-written state with `setState` / `onState`. The sender id is added by the platform. (Each `on*` also exists as `addMessageListener` / `removeMessageListener` and so on.) Watch `onHostChange`: when the host leaves, the longest-standing member becomes host. Limits are 8 KB per message, 20 per second per player and 64 KB of state; the full reference, error codes and a 40-line example are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel). This is not a text chat, so `disableChat` does not apply to it.

## Test with two tabs

1. Serve the game on `localhost` and open `http://localhost:8080/?sdk_debug=true` (`sdk_debug=true` logs every SDK call to the browser console).
2. Host a room. In local mode `inviteLink` returns your own page address with the parameters added, for example `http://localhost:8080/?sdk_debug=true&room=abc`.
3. Open that link in a second tab (or an incognito window). In local mode `inviteParams` is every query parameter of the page (here `{ sdk_debug: "true", room: "abc" }`), `getInviteParam("room")` returns `"abc"` and `?instantJoin=true` makes `isInstantMultiplayer` true, so the "join from the address" path can be tested fully. Open the link without a query string and `inviteParams` is `null`.
4. The local host does not simulate friends' invites or join events: `addJoinRoomListener` never fires. `updateRoom` joins the local room channel, so two tabs that use the same `roomId` can exchange `SDK.game.room` messages and shared state (each tab is a member; the first is the host), and `leftRoom` leaves it. To exercise those, load the game in the [Preview tool](https://www.zokogames.com/preview) and use the event log to confirm the `updateRoom` and `leftRoom` calls arrive, then test the real invite tray with two accounts on the live portal. For a guest, `updateRoom` still resolves but nothing is announced to friends.

## Checklist

- [ ] `updateRoom` on create and join; `leftRoom` on leave.
- [ ] If you use `SDK.game.room`: messages stay under 8 KB and 20 per second, host changes are handled, and no free text is sent without moderation.
- [ ] Parameters from `inviteParams` joined at start; join listener registered.
- [ ] `isInstantMultiplayer` skips the menu.
- [ ] Lobby sizes in the listing match the game; a full room sets `isJoinable: false`.
- [ ] A dropped player does not freeze the room; your server being down shows a message, not a hang.

For the room API in detail, see [multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms).

## Next steps

- [Multiplayer rooms](https://docs.zokogames.com/guides/multiplayer-rooms)
- [Multiplayer](https://docs.zokogames.com/requirements/multiplayer)
