For the complete documentation index, see llms.txt. This page is also available as Markdown.

Matchmaking

Add matchmaking to your browser game with Edgegap's optional JavaScript SDK, ready to extend and customize as your multiplayer project grows.

This SDK is an optional starter kit for JavaScript and TypeScript users, which can be extended and customized later.

💡 Features

  • Complete Examples

  • Promises and Async Loops

  • Tickets, Groups, Teams

  • Match Variables

  • Type Definitions (TypeScript)

  • Backfill Automation

  • Browser, Node.js, Bun, Deno

  • Zero Dependencies

  • Automated Retry

✔️ Preparation

JavaScript SDK contains optional integration utilities for Deployments and Matchmaking. This package officially supports all evergreen browsers, Node.js 22 and newer, Bun, and Deno.

The latest version of JavaScript SDK is 1.1.0. All examples in this documentation are up to date.

Requirements

Allow your game's web origins in Matchmaker configuration

Browsers only call your Matchmaker from pages whose origin is listed in allowed_cors_origins of your Matchmaker configuration. Entries are matched against the full origin, including the scheme and port:

  • https://*.my-game.com matches every subdomain over HTTPS,

  • localhost matches nothing, list local dev servers in full, for example http://localhost:5173 .

Enable TLS Upgrade for your game server's WebSocket port

Set your App Version port protocol to WS and enable TLS Upgrade, so browsers can connect with secure WebSockets (wss://).

Installation

Install the package from npm using your favorite package manager:

Load the browser build in HTML games without a bundler. Everything is exposed under the Edgegap global, with Matchmaking under Edgegap.matchmaking:

Or import it as an ES module:

The package has two entry points:

  • @edgegap/sdk/matchmaking :

    • GroupAgent, ServerAgent, MatchEnvironment, MatchmakingError, Api .

  • @edgegap/sdk - shared utilities:

    • getConnectionUrl, DeploymentEnvironment .

    • Observable, Logger, misc. HTTP helpers.

Verified Sources

This package is only published on npm as @edgegap/sdk, from source code on GitHub. CDNs like jsDelivr and unpkg mirror the npm package. Do not trust unverified sources, packages with similar names outside the @edgegap scope are not affiliated with Edgegap!

When loading from CDN, pin exact version with Subresource Integrity to refuse modified versions.

Update Package

Update to the latest version with your package manager:

When loading from a CDN, change the version in the URL and regenerate your integrity hash.

Some releases may contain breaking changes. This will be indicated by a new MAJOR version.

🍀 Getting Started

This guide assumes basic knowledge of Matchmaking concepts and a running Matchmaker.

Overview

Our SDK utilizes heavily the Observer programming pattern, and lets you consume changes with callbacks, promises, or async iteration - whichever fits your game loop.

This package integrates Matchmaking and Deployments utilities. You may freely reuse any code for your own customized forks and integrations.

This package includes:

  • Service-Specific Utilities:

    • Group Agent - a complete browser client integration to reuse/extend.

    • Server Agent - a complete game server backfill integration to reuse/extend.

    • MatchEnvironment - typed Matchmaking Variables for your game server.

    • Api - endpoint definitions, error handling, and retry automations.

  • Service-Specific Types - request and response types matching Matchmaking API JSON exactly.

  • Shared Utilities - connection URLs, deployment variables, logging, HTTP, observables, etc...

Group Agent

Ticket management, host retrieval, and beacon discovery are performed by Group Agent.

Once instantiated, agent's handler (your game code) must initialize the agent and optionally provide:

  • onMonitorUpdate callback - observe service health changes.

  • onGroupUpdate callback - observe and react to group and host assignment changes.

Once initialized, this agent will automatically provide validations and hook up logging observers, finishing with a single call to the monitoring API endpoint to indicate service health.

Agent's handler is expected to take control and call agent functions from this point:

  • beacons to retrieve a list of available Ping Beacons.

  • measureBeaconsRoundTripTime to provide ping measurements against a given set of beacons.

  • createGroup for the lobby leader to create a joinable group, which friends can be invited to.

  • joinGroup to join an existing group using the group ID sent through 3rd party lobby/backend.

  • setReady to mark group owner and members as ready and begin searching for matches.

  • nextAssignment to wait for the host assignment once the group starts searching.

  • resumeMatchmaking to load a saved group and continue searching in case the page reloaded.

  • stopMatchmaking to delete the ticket (if not matched) and abandon queue.

  • dispose to clear all timers, abort requests, and remove subscribers.

Here are the three different concurrency patterns demonstrated, choose whichever you prefer:

profile and attributes must match a profile in your Matchmaker configuration, gameport is the port name from your App Version. getConnectionUrl returns a wss:// URL for WebSocket ports.

When a new player connection is established, player is expected to send their ticket ID to the game server using your netcode, to correlate connections with Matchmaking Variables. Your game server may be still initializing at this time, so players must retry connection several times:

Server Agent

Server Agent performs backfill creation, detecting ticket assignment, detecting backfill abandonment and removal. It also tracks and re-creates backfills which expired, had the connection grace period elapsed, or were abandoned - to reach the desired team size.

Server Agent keeps track of currently connected players and automatically includes their tickets in new backfills to ensure that backfilled players will match using the configured profile's rules.

Once instantiated, agent's handler (your server code) must initialize the agent and provide:

  • tickets - players already matched to this server, from Matchmaking Variables.

  • onMonitorUpdate callback - observe service health changes.

  • onBackfillUpdate callback - observe and react to backfill changes.

Once initialized, this agent will automatically provide validations and hook up logging observers, finishing with a single call to the monitoring API endpoint to indicate service health.

Server handler is expected to take control and call agent functions from this point:

  • addBackfills to create backfills until assigned players and open backfills reach target team size.

  • playerConnected to prevent replacing initial or backfilled players who never connected.

    • Returns the player's ticket, or null if the ticket isn't assigned to this server - reject such connections.

  • abandonPlayer to signal that a connected player left the server and needs to be replaced.

  • abandonAllBackfills to immediately stop backfilling server and delete backfills.

    • This method should be called before stopping your server. Players who are already assigned at this time need to rejoin matchmaking since the server is shutting down.

    • Assigned backfills at the time of this call can still connect within configured grace period.

  • abandonBackfill to forcefully abandon a specific backfill (custom handler implementations).

  • dispose to clear timers, abort requests, and remove subscribers.

Match Variables

Read Matchmaking Variables in your game server to verify connecting players and assign teams, without calling any API:

match holds matchProfile, matchId, tickets (by ticket ID), groups, teams, and the matched equality and intersection values. Parsing never throws, so the same server runs locally.

Players joining through backfill aren't listed in match.tickets, so servers using Server Agent verify connecting players with agent.playerConnected instead.

🧪 Samples

Get started with samples including a complete functioning integration for both server and client.

Three.js Minigames

Includes five browser games with a full player lifecycle implementation - groups, host assignment retrieval, and connection retries. Demonstrates how to read injected match variables on server side, assign players to teams from a 2-team profile, and stop deployments when the match ends.

Add a new matchmaking profile and game server to expand this example to fit your game easily.

Group Up

Join matchmaking queue with a group of friends, requiring all players to confirm before starting search. The group owner creates a group and shares its ID through your lobby or backend:

Resume After Reload

Save the group when it changes, and resume searching (or reconnect) when the page loads again:

Remove the saved group with localStorage.removeItem('edgegap-group') once the match ends, so players don't reconnect to a finished match.

Backfill

Reuse server capacity and add players to ongoing deployments. Set target team size and wait for players to be added. Includes automated connection grace period and recreating expired backfills, see Server Agent.

Customize your server handler for multi-team or asymmetric team compositions.

⚙️ Customization

This SDK is meant to be extended and modified, though some modifications may be risky:

✅ Handler - safely hook up UI observers and perform minor additions or modifications,

⚠️ Agent - fork the source code and modify player lifecycle management at your own risk,

⚠️ API - write your own integration from scratch, using Api and cherry-picked utilities.

Handlers may observe any events emitted by Server and Group agents as described below.

If you need help, please reach out to us over Discord. For live games support see our ticketing system.

Client Events

Group Agent emits typed events for handlers to observe and consume.

Preview events emitted by observable monitor :

Action Type
Event Code
Event Parameters
Description

🟢 Update

healthy

-

All systems OK.

🟢 Update

unhealthy

-

Unexpected issue.

🔴 Error

monitor_failed

detail

Misconfiguration or unexpected issue.

🔴 Error

beacons_failed

detail

Unexpected issue.

Preview events emitted by observable group :

Action Type
Event Code
Event Parameters
Description

🟢 Update

created

-

Group created OK.

🔴 Error

create_failed

detail

Failed to create group.

🟢 Update

joined

-

Group joined OK.

🔴 Error

join_failed

detail

Failed to join group.

🟢 Update

resumed

-

Group resumed OK.

🔴 Error

not_found

detail?

Not a member of group, or group expired.

🔴 Error

conflict

-

Please abandon current group before trying to create/join a new group, or pass abandon: true.

🟢 Update

member_updated

isReady

Member updated with new Ready value.

🟡 Warn

member_update_failed

-

Can't unready after the group started searching for match.

🔴 Error

update_failed

detail

Failed to update group member.

🔵 Log

polling

attempt, maxAttempts

Agent initiated polling group status. Emitted only with logPollingUpdates: true.

🔵 Log

polling_stopped

-

Agent stopped polling group status. Emitted only with logPollingUpdates: true.

🔴 Error

polling_failed

reason: 'max_retries', detail

Agent exhausted maximum consecutive polling retries. Check service status.

🔴 Error

polling_failed

reason: 'error', detail

Agent received a non-retryable error when polling. Check service status.

🟢 Update

updated

status

Detected group status change while polling.

🟢 Update

abandoned

-

Deleted ticket OK.

🟢 Update

abandon_failed

reason: 'not_found'

Agent couldn't find the group to delete, possibly expired.

🟡 Warn

abandon_failed

reason: 'match_found'

Agent couldn't delete a matched group. Disable abandonment or Backfill Match to replace the player.

🔴 Error

abandon_failed

reason: 'error', detail

Failed to delete group or membership.

🟡 Warn

restart_skipped

-

Group already matched, follow-up action after abandonment was skipped.

🟢 Update

removed

-

Group finished or expired, local reference deleted.

Server Events

Server Agent emits typed events for handlers to observe and consume. Server Agent is only needed for Backfill.

Currently assigned tickets can be read from Server Agent property assignments at any time, and connection times from connectedAt .

Preview events emitted by observable monitor :

Action Type
Event Code
Event Parameters
Description

🟢 Update

healthy

-

All systems OK.

🟢 Update

unhealthy

-

Unexpected issue.

🔴 Error

monitor_failed

detail

Misconfiguration or unexpected issue.

Preview events emitted by observable backfills :

Action Type
Event Code
Event Parameters
Description

🟢 Update

created

backfillId

Backfill created OK.

🔴 Error

create_failed

detail

Unexpected issue with backfill. Check service status.

🔴 Error

capacity_reached

-

Server is full, no backfill created.

🔵 Log

polling

attempt, maxAttempts

Agent initiated polling backfills. Emitted only with logPollingUpdates: true.

🟢 Update

assigned

backfillId, ticketId

Assigned ticket to backfill OK.

🔵 Log

polling_stopped

-

Agent stopped polling, no backfills are left to poll.

🟡 Warn

polling_failed

backfillId, reason: 'not_found'

Not found, removing reference. Backfill most likely expired.

🔴 Error

polling_failed

backfillId, reason: 'max_retries'

Exhausted retries, abandoning all backfills.

🔴 Error

polling_failed

backfillId, reason: 'error', detail

Unexpected issue, abandoning and replacing backfill.

🔵 Log

abandoned

backfillId

Backfill abandoned, removing reference.

🟡 Warn

abandon_failed

backfillId, reason: 'not_found'

Backfill not found, likely expired or duplicate call.

🟡 Warn

abandon_failed

backfillId, reason: 'error', detail

Abandonment failed, removing reference.

🟢 Update

removed

backfillId

Backfill reference removed. Backfill will be replaced automatically if not stopped.

🟡 Warn

remove_failed

backfillId

Backfill reference not found, likely duplicate call.

Last updated

Was this helpful?