> 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/tools-and-integrations/playfab-bridge.md).

# Deploy from PlayFab

Keep PlayFab Matchmaking and start an Edgegap dedicated server near the players for every match, from two Azure Functions.

Keep **PlayFab** for player accounts and matchmaking queues, and run every match on its own **Edgegap** dedicated server, placed near the matched players. Two Azure Functions connect them:

* When PlayFab finds a match, `StartEdgegapDeployment` asks Edgegap for a server near the players and returns right away.
* When the server is ready, Edgegap calls `EdgegapDeploymentReady`, which writes the server's address and a **join token** to each player's **read-only** PlayFab data.

The Edgegap API token and the PlayFab title secret key stay in the Function App's settings. The game client holds only the title ID, and the game server holds no secret at all. It admits only the players PlayFab matched.

```
Client --LoginWithCustomID / CreateMatchmakingTicket--> PlayFab queue (server allocation off)
PlayFab --rule on match_found--> Azure Function StartEdgegapDeployment
             GetMatch + player locations --POST /v2/deployments--> Edgegap
Edgegap --webhook_on_ready--> Azure Function EdgegapDeploymentReady
             reads the deployment + match --UpdateUserReadOnlyData "EdgegapServer"--> each player
                                              (host, port, join token)
Client polls GetUserReadOnlyData --> connects to host:port, sends its join token --> server stops itself when empty
```

The sample project, **SpaceEdge**, is on [GitHub](https://github.com/edgegap/backend-game-sample-unity-playfab-matchmaker-fishnet-spaceedge). It was tested end to end on 21 October 2026 with Unity 2021.3.45f2, FishNet 3.11.14 (Tugboat, UDP 7770), Node.js 22 on Azure Functions (Flex Consumption), and a PlayFab queue of 2: two clients were matched by PlayFab, and the server address reached both about 8 seconds after the function call. Join tokens and the build with the Edgegap Unity plugin came after that run, and were tested with unit tests and a local server container.

{% hint style="info" %}
**Using a coding agent?** The `edgegap-playfab` skill in the [Edgegap MCP server](https://docs.edgegap.com/docs/mcp-integration.md) ships the same Azure Functions, scripts that deploy them and create the queue, the Unity client and server code, and a chain test to run before you add the rule.
{% endhint %}

## 🚀 Getting Started

Before you start, you need:

* A **working Edgegap app version** of your game server: a server you deployed and joined at least once. See [Unity](https://docs.edgegap.com/unity.md), [Unreal Engine](https://docs.edgegap.com/unreal-engine.md) or [Godot](https://docs.edgegap.com/godot.md). Name its game port `gameport`. The server needs no PlayFab settings or secrets.
* A **PlayFab title** with Matchmaking, its Title ID, and a secret key.
* An **Azure subscription** and the [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli). Testing fits in the Flex Consumption plan's monthly free grant.
* An **Edgegap API token**, from [Dashboard → User Settings → Tokens](https://app.edgegap.com/user-settings?tab=tokens). It goes only in the Function App's settings.

{% hint style="warning" %}
Older versions of this guide used JavaScript CloudScript and passed the PlayFab title secret to the game server. Microsoft now calls JavaScript CloudScript "classic" and points new work to [CloudScript using Azure Functions](https://learn.microsoft.com/en-us/gaming/playfab/live-service-management/service-gateway/automation/cloudscript-af/quickstart). Use the Azure Functions below, and remove any PlayFab secret from your server.
{% endhint %}

## 1. Game Server

The server has to listen on its port, admit only the matched players, and stop itself when the match is over.

* **Listen on a fixed port**, the one declared as `gameport` on the app version. The sample listens on UDP 7770.
* **Stop its own deployment** when nobody joins, or after the last player leaves: send `DELETE` to `ARBITRIUM_DELETE_URL` with the header `authorization: <ARBITRIUM_DELETE_TOKEN>`. Both are [injected into every deployment](https://docs.edgegap.com/learn/orchestration/deployments.md#injected-environment-variables). The sample stops after 120 seconds if nobody connects, or 30 seconds after the last player leaves.
* **Admit only the matched players.** `StartEdgegapDeployment` passes the match's join tokens in the hidden variable `EDGEGAP_JOIN_TOKENS` (comma-separated), and each client gets its own token with the address. Make every client send its token right after connecting, and disconnect clients whose token isn't in the list. Let a new connection with a known token replace the old one, so a player whose game crashed can rejoin before the old connection times out.
* Remove any PlayFab GSDK calls. PlayFab Multiplayer Servers aren't used.

`StartEdgegapDeployment` also passes `PLAYFAB_MATCH_ID` and `PLAYFAB_QUEUE_NAME` as environment variables, for logs or game logic.

{% hint style="info" %}
In the sample, `EdgegapServer.cs` does all of this and adds itself at runtime in server builds, with no scene setup. `JoinTokenAuthenticator.cs` checks the tokens with a FishNet authenticator; with another netcode, use its connection approval or first message instead. If you use FishNet, keep **Start On Headless** off on the `ServerManager`: `EdgegapServer.cs` starts the server on the known port.
{% endhint %}

Build, containerize and push the server as usual, then create the app version: one port named `gameport` (UDP 7770 for the sample), 0.5 vCPU and 1 GB, and a max duration of 60 minutes. No environment variables are needed on the version: the function passes them per match.

{% hint style="warning" %}
The default Dockerfile of the Edgegap Unity plugin, up to version 3.2.1, runs `env` before the server, so the deployment logs list its variables, including the join tokens and the self-stop token. Remove `env;` from the Dockerfile's `CMD` if your logs are shared.
{% endhint %}

## 2. PlayFab Matchmaking Queue

1. In Game Manager, open **Multiplayer → Matchmaking** and create a queue (the sample uses `edgegap-fishnet`). For a first test, a match size of 2 with no rules matches any two players.
2. Turn **Enable server allocation** **off**: PlayFab only forms the match, and Edgegap hosts the server.
3. If players sign in with `LoginWithCustomID` or a device ID, open **Title settings → API Features** and untick **Disable player creation using Client/LoginWithCustomId**. New titles have it ticked, and logins fail with `PlayerCreationDisabled`.
4. In **Title settings → Secret Keys**, create a secret key for the Azure Functions.

{% hint style="warning" %}
**Moving a live queue off PlayFab Multiplayer Servers?** Clients you already shipped read the server from `GetMatch`, which stops returning it once allocation is off. Test on a copy of the queue, and ship the new client before you switch.
{% endhint %}

## 3. Azure Functions

Create one resource group, a storage account, and a Flex Consumption Function App on Node.js 22. PlayFab recommends a US West region:

```bash
az group create -n rg-edgegap-playfab -l westus2
az storage account create -n <storageaccount> -g rg-edgegap-playfab -l westus2 --sku Standard_LRS
az functionapp create -g rg-edgegap-playfab -n <function-app> --storage-account <storageaccount> \
  --flexconsumption-location westus2 --runtime node --runtime-version 22
```

Deploy the sample's `azure-functions` folder (Node.js 22, no PlayFab or Edgegap SDK):

```bash
cd azure-functions
npm ci --omit=dev
# zip host.json, package.json, src/ and node_modules/ into bridge.zip, then:
az functionapp deployment source config-zip -g rg-edgegap-playfab -n <function-app> --src bridge.zip
```

Add the app settings (Function App → Settings → Environment variables):

| Setting                                    | Value                                                                                                                  |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `PLAYFAB_TITLE_ID`                         | Your title ID.                                                                                                         |
| `PLAYFAB_SECRET_KEY`                       | The title secret key.                                                                                                  |
| `EDGEGAP_API_TOKEN`                        | Your Edgegap API token, without the `token` prefix.                                                                    |
| `EDGEGAP_APP_NAME` / `EDGEGAP_APP_VERSION` | Your application and version names.                                                                                    |
| `EDGEGAP_READY_WEBHOOK_URL`                | `https://<function-app>.azurewebsites.net/api/EdgegapDeploymentReady?code=<function key>`                              |
| `EDGEGAP_PORT_NAME`                        | Optional, defaults to `gameport`.                                                                                      |
| `EDGEGAP_QUEUES`                           | Optional, comma-separated. `match_found` fires for every queue of your title; only these queues get an Edgegap server. |
| `FALLBACK_LATITUDE` / `FALLBACK_LONGITUDE` | Optional. Used when PlayFab has no location for any player.                                                            |

Get each function's key with `az functionapp function keys list -g rg-edgegap-playfab -n <function-app> --function-name <name>`.

{% hint style="danger" %}
Function keys are secrets: they're part of the function URLs, so don't commit or share those URLs. Never put the Edgegap token or the PlayFab secret key in the game client, the game server or your repository.
{% endhint %}

### StartEdgegapDeployment

Runs on PlayFab's `match_found` event:

1. Reads `MatchId` and `QueueName` from the event.
2. Gets the match members with `Match/GetMatch`, and each player's location with `Server/GetPlayerProfile` (PlayFab geolocates their login IP).
3. Computes one join token per player: an HMAC of the match ID and the player's PlayFab ID, keyed with the title secret, so `EdgegapDeploymentReady` can compute the same tokens later without storing them.
4. Calls `POST https://api.edgegap.com/v2/deployments` with the players' coordinates, a tag with the first 20 characters of the match ID, the join tokens in the hidden variable `EDGEGAP_JOIN_TOKENS`, and the ready and error webhooks.
5. Returns in about a second. It never waits for the server: PlayFab's call times out after 10 seconds, and a server takes 5 to 30 seconds to be ready.

```javascript
// azure-functions/src/lib/edgegap.js
return call('POST', '/v2/deployments', {
  application: requireSetting('EDGEGAP_APP_NAME'),
  version: requireSetting('EDGEGAP_APP_VERSION'),
  users: locations.map((l) => ({ user_type: 'geo_coordinates', user_data: l })),
  tags: [matchTag(matchId), 'playfab'],
  environment_variables: [
    { key: 'PLAYFAB_MATCH_ID', value: matchId, is_hidden: false },
    { key: 'PLAYFAB_QUEUE_NAME', value: queueName, is_hidden: false },
    {
      key: join.ENV_KEY, // EDGEGAP_JOIN_TOKENS
      value: players.map((p) => join.joinToken(matchId, p.playFabId)).join(','),
      is_hidden: true,
    },
  ],
  webhook_on_ready: { url: webhook.toString() },
  webhook_on_error: { url: errorWebhook.toString() },
});
```

### EdgegapDeploymentReady

Called by Edgegap through the ready webhook, not by PlayFab, so don't register it in PlayFab.

1. It doesn't trust the webhook body: it reads the deployment from the Edgegap API and checks that it carries this match's tag.
2. It reads the match members again from PlayFab.
3. It writes `{"matchId", "status", "host", "port", "joinToken"}` to each player's **read-only** data under the key `EdgegapServer`, with `Server/UpdateUserReadOnlyData`. Clients can read it but can't change it.
4. If the server failed, it writes `status: "error"`, so clients stop waiting.

### Register the Function and Add the Rule

1. In **Automation → CloudScript → Functions → Register Function**, register `StartEdgegapDeployment` with its URL, including `?code=<function key>`.
2. In **Automation → Rules → New Rule**, set the event type to `playfab.matchmaking.match_found` and add the action **Execute Azure Function → StartEdgegapDeployment**.

{% hint style="info" %}
Once the rule exists, calling `StartEdgegapDeployment` by hand for the same match starts a second server. Test the functions by hand before you add the rule.
{% endhint %}

## 4. Game Client

1. Sign the player in to PlayFab (the sample uses `LoginWithCustomID`; use your game's login). The client holds only your title ID.
2. Create a ticket in the queue with `Match/CreateMatchmakingTicket`, and check it with `Match/GetMatchmakingTicket` every 6 seconds until its status is `Matched`. PlayFab allows 10 checks per minute per ticket.
3. Read `EdgegapServer` with `Client/GetUserReadOnlyData` every 2 to 3 seconds. Ignore any value whose `matchId` isn't this match's: it's left over from an earlier match.
4. Connect to `host:port`, and send `joinToken` as soon as the connection is up. On `status: "error"`, show an error and let the player queue again.

The sample's `PlayFabMatchmakingClient.cs` does this with `UnityWebRequest` and `JsonUtility` only, with no PlayFab SDK. The only netcode-specific code is the connect call:

```csharp
// FishNet (Tugboat UDP); JoinTokenAuthenticator sends the token once connected
JoinTokenAuthenticator.Install(InstanceFinder.NetworkManager).Token = joinToken;
InstanceFinder.TransportManager.Transport.SetClientAddress(host);
InstanceFinder.TransportManager.Transport.SetPort(port);
InstanceFinder.ClientManager.StartConnection();
```

If your game already uses the PlayFab SDK, make the same calls through it.

## 5. Testing

1. Make sure no other deployment is running: the free tier runs one deployment at a time.
2. Start two clients as two different PlayFab players. On one machine, they share PlayerPrefs, so give each its own ID: the sample takes `-playfabCustomId player-a` and `-playfabCustomId player-b`.
3. Start matchmaking on both. Once PlayFab matches them, a deployment tagged with the start of the match ID appears in the [Edgegap dashboard](https://app.edgegap.com/deployment-management/deployments/list), and both clients connect to it a few seconds later.
4. Quit both clients: the server stops itself.

| Symptom                                           | Fix                                                                                                                                                              |
| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PlayerCreationDisabled` at login                 | Untick **Disable player creation using Client/LoginWithCustomId** (step 2).                                                                                      |
| Matched, but no server address                    | Check the Function App logs (Application Insights, or each function's Monitor tab), and that the rule's event type is exactly `playfab.matchmaking.match_found`. |
| `Edgegap POST /v2/deployments failed (401)`       | `EDGEGAP_API_TOKEN` is wrong, or still has the `token` prefix.                                                                                                   |
| Webhook writes nothing                            | `EDGEGAP_READY_WEBHOOK_URL` must contain the `code=` key of `EdgegapDeploymentReady`.                                                                            |
| Both clients sign in as the same player           | Run them with different `-playfabCustomId` values.                                                                                                               |
| A deployment starts but nobody connects           | It's the server: deploy your version by hand and join it directly.                                                                                               |
| Server log `rejected: not a player of this match` | The client sent no token, or a token from another match. Check that both functions run the same code with the same `PLAYFAB_SECRET_KEY`.                         |

Moving from PlayFab Multiplayer Servers? See [Switch from PlayFab](https://docs.edgegap.com/docs/hosting-migration/switch-from-playfab.md) for what changes.

Prefer a hosted matchmaker with no functions to run? See [Edgegap Matchmaking](https://docs.edgegap.com/learn/matchmaking.md).
