> ## Documentation Index
> Fetch the complete documentation index at: https://docs.patch.gg/llms.txt
> Use this file to discover all available pages before exploring further.

# Game backend

> Who's playing, and rooms for playing together, for your browser game, with no server of your own.

Patch gives a browser game what it would otherwise need a backend for. Players sign in to Patch, never to your game. They play together in rooms Patch runs. Your game keeps its own rules, and its progress, on the player's device.

`window.patch` is there when your game plays on Patch. Opened anywhere else it isn't, so check for it and keep the game playable without it.

## Before it's out

Once Patch has checked a version's files, it has a **test link**: its play page with `?release=`, which plays that version on Patch, sign-in and rooms included, before you publish it. Anyone signed in who has the link can play it, so send it to friends to try multiplayer together. Your game's players never get it: it plays at its own address, with rooms of its own, and stops once the version is turned down. Publishing answers with `test_link`, and its invite links keep you on that version. A test link reaches the game's own files, Patch's rooms and [direct links](#direct-links): [your own server](#your-own-server)'s hosts apply once Patch has looked at them and the version is published.

## Who's playing

```js theme={null}
const player = await window.patch?.getPlayer();
if (player) greet(player.name); // "Mira"
```

A player is `{ id, handle, name, picture }`:

| Field | What it is |
| - | - |
| `id` | Their id in your game only. Keep your records by it. Another game sees another id for them. |
| `handle` | Their Patch handle, lowercase, or `null` until they've picked one. |
| `name` | Their handle as they write it. |
| `picture` | The address of their picture, or `null`. |

On Patch, everyone signs in before they play, so `getPlayer()` has who's playing. Where nobody has, ask:

```js theme={null}
const player = await window.patch.signIn();
```

Patch offers sign-in over your game. If they sign in, the game loads again, signed in. If they'd rather not, `signIn()` resolves with `null` and your game plays on. `window.patch.player` is the player Patch last said, and `playerchange` fires on `window.patch` when it changes.

## Rooms

Players in your game together. Patch passes their messages on and keeps who's in the room, its host and its data. There's no server to run and nothing to declare.

```js theme={null}
const code = (await patch.getLaunch()).room; // the invite link's room, or this tab's before a reload
const room = code ? await patch.rooms.join(code) : await patch.rooms.create({ max: 4 });

room.on("message", (message, fromId, at) => moveOther(fromId, message)); // at: the room's time
room.on("join", (player) => addPlayer(player));
room.on("leave", (player) => removePlayer(player));
room.send({ x: 10, y: 4 }); // to everyone else

const { link, copied } = await room.invite(); // Patch copies the invite link for the player
```

* `patch.rooms.create({ max, listed, data, keep, anyRelease })` makes a room with a 6-character code of capital letters and digits, `room.code`, to show and type. `max` is 1 to 100 players (8 by default). `listed: true` lets quick matches find it. `keep` is how many minutes an empty room waits for its players to come back with its data: 2 by default, up to 1440 (a day) for turn-based games. `anyRelease: true` lets players on other versions in. Anything out of range, or an option a room doesn't take, throws `bad_options`: Patch makes every room's code, so a game can't choose one. Rooms are for browser games; a PC game or a mod brings its own server.
* `patch.rooms.join(code)` joins one, and `patch.rooms.quickMatch({ max, data, keep })` joins the fullest listed room with space and the same `max`, or makes one: a **Play online** button. A room nobody's in waits for its own players and isn't offered to strangers. The host's `room.setListed(false)` takes the room off quick matches once a match starts.
* `patch.getLaunch()` gives `{ room }`: the room of the invite link your game was opened from, or the room this tab was in before a reload. Join it at the start.
* `room.players` is everyone, in the order they joined: `{ id, name, handle, host }`, each by their Patch name: everyone playing on Patch has signed in.
* **The host.** `room.host` is the host's id, and `room.isHost` says whether that's you. Patch picks the first player, and when the host leaves, or its page has been hidden for 5 seconds, whoever has been in the room longest and is still on screen (the `host` event, with their id). Let the host run what everyone shares, such as the world, the clock or the bots, and send it to the others.
* **The room's data.** The host's `room.setData(data)` replaces it. Every other player gets it (`room.data`, and the `data` event), and so does anyone who joins later: the map, the mode, whose turn it is. It's up to about 16 KB as JSON, and more throws `too_big` at once: keep a big world in messages, or rebuild it from a seed. The host's own `room.data` is the new data straight away.
* **Messages.** `room.send(message, { to })` sends any JSON up to 16 KB, in order, to everyone else or to one player. Each player sends at most 30 a second, bursts of 60, room data included: past that a message is dropped and the sender gets `too_fast`. Send state 10 to 20 times a second and smooth it on the others' screens.
* **The room's clock.** `room.now()` is the room's time, the same on every screen: start countdowns and race clocks from it. It keeps counting while the room waits empty.
* **Testing.** Patch's own test opens the game alone with `?patch-test=1`: with it and no room, play alone. To try several players before it's out, open its [test link](#before-its-out) and send its invite link to others, or open it in several browser profiles.
* **Late joiners.** A message reaches only who's in the room when it's sent, so a player who joins late gets the room's data and nothing sent before. Have the host send them what they missed when they join, with `{ to: player.id }`.
* **Leaving.** `room.leave()` leaves, and `close` fires when the room's connection ends. A player who reloads comes back as the same player: join the same code again.
* **Versions.** Only players on the same version of your game share a room. Someone on an older page gets `room_needs_update`, and should reload.
* Errors carry a `code`: `room_not_found`, `room_full`, `room_needs_update`, `code_taken`, `bad_code`, `bad_options`, `not_host`, `too_big`, `too_fast`, `room_unreachable`, or `no_patch` (not on Patch).
* To test with several players, open the play page in several browser profiles. Opening it with `?patch-test=1` opens your game with it.

## Direct links

For fast games, where every hundredth of a second shows: two players in a room link directly, and a message that arrives late can be skipped instead of holding up the rest. Patch relays the link and sets it up through the room, so there's nothing to run, declare or pay for, and it works at a test link.

```js theme={null}
// Make a link: the other player's room fires "link" with theirs.
const link = await room.link(otherPlayer.id);
room.on("link", (link) => listen(link));

link.on("message", (message) => moveOther(link.id, message));
link.send({ x: 10, y: 4 }, { reliable: false }); // positions: now or never
link.send({ hit: "zombie-7" });                  // events: always, in order
```

* `room.link(id)` resolves once the link with that player is open. Their room fires `link` with it, so make links from one side, such as the host to each player as they join, or from both: two players linking at once make one link.
* `link.send(message, { reliable })` sends any JSON up to 64 KB. By default it arrives, in order. With `reliable: false` it goes at once or not at all, in no order: for state you send many times a second. Past what the link can carry it's dropped, and a reliable message throws `too_fast`.
* `link.on("message", fn)` and `link.on("close", fn)`; `link.close()` ends it. A link ends when either player leaves the room, and when the room closes: link again after rejoining.
* **Through Patch.** Links go through Patch's relay, near each player, so players never see each other's addresses and it connects on any network. Only players signed in to Patch get links, as on Patch's play page.
* **Your own WebRTC.** An engine with its own WebRTC code can use the relay: `new RTCPeerConnection({ iceServers: await room.iceServers() })`, with the room carrying its messages. Patch keeps the page's connections to the relay.
* Errors carry a `code`: `no_direct_links` (not on Patch, or not signed in), `link_failed` (couldn't link, or the player left), `link_closed`, `too_big` or `too_fast`.

## Your own server

Rooms cover most games. A game whose rules no player's browser may decide, such as checking a lap before it counts, or that keeps what players do, can bring its own server.

**Know who's connecting.** `getPlayerToken()` gives a token, signed by Patch for your game, that says who's playing. Send it to your server and check it there:

```js theme={null}
const token = await window.patch.getPlayerToken(); // null when nobody's signed in
socket.send(JSON.stringify({ type: "hello", token }));
```

```js theme={null}
import { createRemoteJWKSet, jwtVerify } from "jose";

const PATCH_KEYS = createRemoteJWKSet(new URL("https://patch.gg/api/v1/games/keys"));

export async function whoIs(token) {
  const { payload } = await jwtVerify(token, PATCH_KEYS, {
    issuer: "https://patch.gg",
    audience: "<your project's id>",
    algorithms: ["ES256"],
  });
  return { id: payload.sub, handle: payload.handle, name: payload.name };
}
```

* Tokens last 15 minutes, so call `getPlayerToken()` each time you connect.
* `aud` is your project's id, `sub` the player's `id`. The token also carries `game`, `handle`, `name` and `picture`.
* Treat a token like a password: don't log it, and send it only to your own server.

**Let your game reach it.** A game on Patch only reaches its own files. Name your server's hosts in your game's settings, and the ICE servers if it links players over WebRTC with its own servers rather than [direct links](#direct-links):

```bash theme={null}
curl -X PATCH https://patch.gg/api/v1/games/<owner>/<slug>/settings \
  -H "Authorization: Bearer $PATCH_API_KEY" -H "content-type: application/json" \
  -d '{ "connects_to": ["wss://rooms.example.com", "https://rooms.example.com"] }'
```

* Each host is `https://` or `wss://`, a host name and an optional port, with no path. `*.example.com` covers one level of subdomains.
* Your next version takes them as it's published, and a person at Patch looks at the hosts before it goes out.
* Your server sees requests from your game's own address on Patch, `https://<id>-production.patchusercontent.com`.


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