> For the complete documentation index, see [llms.txt](https://docs.edgegap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.edgegap.com/docs/sample-projects/web-games/html5-phaser.md).

# HTML5 Multiplayer (Phaser)

HTML5 multiplayer game tutorial: a Phaser browser game with an authoritative Node.js WebSocket server per match, hosted on Edgegap with matchmaking.

Learn how to make an HTML5 browser game online multiplayer, with one authoritative server per match on Edgegap.

![Splat Arena: a paintball match in the browser](https://raw.githubusercontent.com/edgegap/netcode-sample-html5-phaser/main/docs/images/gameplay.jpg)

Splat Arena is a 2D paintball free-for-all for 1 to 8 players. The browser client is [Phaser 4](https://phaser.io/) with no bundler and no build step, and each match runs on its own Node.js WebSocket server, started by Edgegap close to its players.

This sample shows:

* **Authoritative server**: the browser only sends inputs (keys, aim, fire). The server moves everyone, fires the paint, decides hits and keeps score, so editing the page in devtools can't make a player faster or score a hit.
* **Smooth rendering from 20 Hz snapshots**: the client eases each player toward the latest server position and moves bullets along their velocity between updates.
* **Bots**: a player waiting alone gets a match after 20 seconds, and bots fill the arena up to 4 players.
* **Find match from the page** with the [Edgegap JavaScript SDK](https://www.npmjs.com/package/@edgegap/sdk), loaded from a CDN with an import map.
* **`wss://` from an `https` page**: Edgegap terminates TLS on the port, so the server stays plain `ws`.
* **One server per match that stops itself** when the match ends, so you only pay while people play.

{% hint style="info" %}
See the [sample repository](https://github.com/edgegap/netcode-sample-html5-phaser) for the game, the game server, the matchmaker configuration and end-to-end tests of the whole flow.
{% endhint %}

## ✔️ Preparation

Before we start, you will need:

* [HTML5 Phaser sample](https://github.com/edgegap/netcode-sample-html5-phaser), pushed to your own GitHub repository.
* [Node.js](https://nodejs.org/) 22 or newer, to run the server and page locally.

☑️ Try the game locally first:

{% code collapsedlinecount="10" %}

```bash
npm install
npm test
npm start
```

{% endcode %}

`npm test` plays a full match with two headless players and a bot. `npm start` runs the game server on `ws://localhost:7777`.

☑️ In a second terminal, run `npm run client`, open `http://localhost:8080` in two browser tabs and click **Local server :7777** in both. The match starts 15 seconds after the first player joins. Move with WASD or the arrow keys, aim with the mouse, and click or press Space to fire. First to 10 hits wins.

## 🕹️ How the Multiplayer Works

### 1. One WebSocket, JSON Messages

| Direction        | Message                                                                                                               |
| ---------------- | --------------------------------------------------------------------------------------------------------------------- |
| client to server | `{t:"hello", name, ticket}` once, then `{t:"input", mx, my, aim, fire}` when input changes (at most \~30/s)           |
| server to client | `{t:"welcome", id, info}` once (arena size and walls), then `{t:"state", phase, timer, players, s}` 20 times a second |

The server clamps every input it receives and runs the rules in `server/game.js` 30 times a second. `server/room.js` runs the match (`waiting`, `countdown`, `playing`, `over`), adds bots, broadcasts state, and stops the deployment when the match is over.

The client only draws. `client/scene.js` eases each player toward the latest snapshot and sends intents, never positions:

{% code collapsedlinecount="10" %}

```js
// Every frame: ease toward the latest server position (snapshots arrive every 50 ms).
p.view.x += (p.x - p.view.x) * t;
// Bullets keep moving along their velocity between snapshots.
b.x += b.vx * dt;
// Send intents, never positions.
this.match.send({ mx, my, aim, fire });
```

{% endcode %}

{% hint style="success" %}
**Only `client/scene.js` depends on Phaser.** Swap it for a plain `<canvas>` 2D context, PixiJS, Kaplay or three.js and keep `main.js`, `net.js` and the whole server as they are.
{% endhint %}

✅ You may now proceed to the next step.

## ⚡ Deploy and Connect

### 2. Build the Server Image

☑️ To get started, you'll need to [create a free account with Edgegap](https://app.edgegap.com/auth/register). No credit card required.

☑️ Find your [Container Registry](https://docs.edgegap.com/learn/advanced-features/edgegap-container-registry.md) project name and credentials.

☑️ In your GitHub repository, open **Settings**, then **Secrets and variables**, then **Actions**, and add:

* variable `EDGEGAP_REGISTRY_PROJECT` - your registry project name,
* secret `EDGEGAP_REGISTRY_USERNAME` - your registry username,
* secret `EDGEGAP_REGISTRY_TOKEN` - your registry token.

☑️ Run the **Server image** workflow from the **Actions** tab. It plays the local match test, then builds and pushes `registry.edgegap.com/<project>/splat-arena:<tag>`, tagged with the build time. The tag is shown in the run's summary.

☑️ To build on your own machine instead, sign in to Edgegap's Container Registry with Docker, using your registry project name, username and token:

{% tabs %}
{% tab title="Bash (Linux)" %}

```bash
project='<REGISTRY_PROJECT>';
username='robot$<REGISTRY_ORGANIZATION_ID>+client-push';
token='<REGISTRY_TOKEN>';

echo "$token" | docker login registry.edgegap.com -u "$username" --password-stdin 2>&1
```

{% endtab %}

{% tab title="PowerShell (Windows)" %}

```powershell
$project = '<REGISTRY_PROJECT>'
$username = 'robot$<REGISTRY_ORGANIZATION_ID>+client-push'
$token = '<REGISTRY_TOKEN>'

echo "$token" | docker login registry.edgegap.com -u "$username" --password-stdin 2>&1
```

{% endtab %}
{% endtabs %}

☑️ Then build and push the image:

{% code collapsedlinecount="10" %}

```bash
docker build --platform linux/amd64 -t registry.edgegap.com/<project>/splat-arena:<tag> .
docker push registry.edgegap.com/<project>/splat-arena:<tag>
```

{% endcode %}

{% hint style="danger" %}
:x: **DO NOT - overwrite existing tags or use `latest`  tag** - this will deploy an outdated cache.\
:white\_check\_mark: **DO - always increase your version tag** and deploy the new build.
{% endhint %}

✅ You may now proceed to the next step.

### 3. Create the App Version

☑️ [Create an application](https://app.edgegap.com/application-management/applications/list) named `splat-arena`, with one version named after your tag:

* **Image**: registry `registry.edgegap.com`, repository `<project>/splat-arena`, tag `<tag>`,
* **Resources**: 0.25 vCPU and 512 MB memory,
* **Port**: `7777`, name `gameport`, protocol **WS**, with **TLS Upgrade** enabled,
* **Restart policy**: Never,
* **Max duration**: 30 minutes, as a safety net: the server stops itself.

{% hint style="warning" %}
**TLS Upgrade** lets browsers on `https` pages connect to `wss://<id>.pr.edgegap.net:<port>`. Edgegap terminates TLS and forwards plain WebSocket traffic to port `7777`.
{% endhint %}

{% hint style="info" %}
Free Tier is limited to 2 Applications, 2 versions, and 10 GB of Container Registry storage.
{% endhint %}

☑️ To try one server before adding matchmaking, deploy the version from the dashboard and copy its `wss://<id>.pr.edgegap.net:<port>` address. Open `http://localhost:8080/?server=wss://<id>.pr.edgegap.net:<port>` in two tabs, or play a match with two headless players:

{% code collapsedlinecount="10" %}

```bash
SERVER_URL=wss://<id>.pr.edgegap.net:<port> node tools/e2e.mjs 2
```

{% endcode %}

The deployment stops itself a few seconds after the results screen.

✅ You may now proceed to the next step.

### 4. Create the Matchmaker

☑️ Set `application.version` in the sample's `matchmaker/splat-arena.json` to your version, and add the address of your page to `allowed_cors_origins` (scheme, host and port, for example `https://<you>.github.io`).

☑️ Open the [Matchmaker](https://app.edgegap.com/matchmaker-management-v2/matchmakers/list) page in the dashboard, click **Create**, upload the config, and click **Create and Start**.

The `splat-arena` profile matches 2 to 8 players. After 20 seconds, a player waiting alone gets a server, and bots fill the arena.

☑️ When the matchmaker shows **Online**, copy its **API URL** and **Auth Token** into `client/config.local.js`, a copy of `client/config.js`.

{% hint style="success" %}
The **matchmaker Auth Token is safe to ship in web pages**: it can only ask for matches. Never put your Edgegap API token in a page or in the server image.
{% endhint %}

✅ You may now proceed to the next step.

### 5. Find a Match

☑️ Open your page in two browser tabs and click **Find match** in both within 20 seconds.

Each page:

1. joins the matchmaker and waits for `HOST_ASSIGNED`,
2. connects to `wss://<fqdn>:<port>` and sends its ticket ID,
3. plays: it sends inputs and draws the state the server sends back.

The game server:

1. waits for the matched players, then fills the empty seats with bots,
2. runs the rules 30 times a second and sends snapshots 20 times a second,
3. stops its own deployment after the results screen.

🙌 Both players are now in the same match, on a server placed near them.

☑️ To test the whole path without a browser, run the end-to-end test. It queues two headless players, plays a match, and waits for the deployment to stop itself:

{% code collapsedlinecount="10" %}

```bash
MM_URL=<API URL> MM_TOKEN=<Auth Token> node tools/e2e.mjs splat-arena 2
```

{% endcode %}

## 📦 Ship Your Game

* Host the page anywhere: `client/` is static files with no build step. The sample includes a GitHub Pages workflow. On itch.io, add `https://html-classic.itch.zone` to `allowed_cors_origins`.
* Turn `inspect` off in the matchmaker config and list only your real origins before launch.
* Set `REQUIRE_TICKET=1` on the app version so only matched players can join a server.
* To ship new rules, push a new image tag and point the app version at it. New matches use it, and running ones keep the old build. Client changes only need the page to be published again.

{% hint style="info" %}
Using a coding agent? The `edgegap-html5` skill in [Edgegap's agent skills](https://github.com/edgegap/llm-agent-skills) holds the server templates, the Phaser client and the tests, and walks your agent through the same steps for your own HTML5 game.
{% endhint %}
