View as Markdown

How to integrate Nakama with a Photon Fusion game

Photon Fusion is a Unity networking library that keeps game state in sync across players during a multiplayer match. Nakama is an open-source game backend that handles player accounts, friends, leaderboards, and more. Together, they let you build highly performant multiplayer games where players keep their identity, friends, and progress from one session to the next.

This guide uses the Nakama and Photon Fusion demo, which adds Nakama to Photon’s Fusion Starter sample. The guide focuses on three features that use both services:

  • Authentication: Players sign in to Nakama. When they join a match, Photon Cloud sends their Nakama session token back to Nakama to check that it’s valid.
  • Friends: Players add each other as friends in Nakama and join a friend’s Fusion match from their friends list.
  • Leaderboards: The winner’s time from a Fusion match is saved to a Nakama leaderboard. To reduce cheating, the server checks for suspicious scores before saving it.
The platformer during a round, with a timer showing the elapsed time
The Fusion Starter platformer with Nakama added.
Looking for a quick start?
To get up and running quickly with the demo game, see the Nakama and Photon Fusion demo.

How the demo connects to Photon and Nakama #

The game client calls Photon Cloud and Nakama separately. The two services talk to each other when a player joins a match: Photon Cloud asks Nakama to check the player’s session token. This makes sure only players signed in to Nakama can join, and tells Photon which Nakama account each player belongs to. This diagram shows the calls this guide covers:

Sequence diagram with three participants: the game client, Photon Cloud, and Nakama. The game client authenticates with Nakama using its device ID and receives a session token. It starts a Fusion game with the token, and Photon Cloud calls the photon_auth RPC on Nakama, which accepts or rejects the player. Photon Cloud then tells the game client whether it joined the match. The client then sets its Nakama status to In Game with the session name, and Nakama sends the status to the player's friends. When the player wins, the client writes the time to a leaderboard, and a before hook checks it.

Key terms #

  • Shared mode: A Photon Fusion topology where clients connect through Photon’s cloud and there’s no dedicated host. Each client has state authority over the objects it spawns.
  • Custom authentication: A Photon feature where Photon Cloud asks your own server whether a player can connect.
  • Status: A short text message a player publishes through their Nakama socket. Other players who follow them receive it in real time. See Status.
  • Before hook: A server function that runs before Nakama handles a client request. It can change the request or reject it.
  • Authoritative leaderboard: A leaderboard that only the server can write to. Clients can read it but can’t submit scores.

Before you begin #

This guide doesn’t cover every Fusion or Nakama feature. Instead, it walks through how the demo implements authentication, friends, and leaderboards. Clone the demo project to follow along in the code.

The demo includes a Nakama server you can run locally and a Unity client that’s already set up to use Nakama. To see how they were set up, or to read about the concepts behind them, see:

Run the demo #

To run the demo locally and change it, you need Unity 6, Docker Desktop, and a free Photon account with a Fusion 2 App ID.

Start the server #

The demo’s nakama-server/ folder contains a Go module and a Docker Compose file that builds Nakama with the module and runs it.

  1. From a terminal, go to the demo’s nakama-server/ folder.
  2. Run docker compose up --build. The first build takes a few minutes.
  3. Wait until the logs show Startup done.
  4. Open the Nakama console at http://localhost:7351, and sign in with the username admin and the password password.

Leave the server running while you work through this guide.

Open the project in Unity #

  1. In Unity Hub, select Add > Add project from disk, and select the UnityFusionDemo folder in the demo repository. The first import downloads the project’s packages, including the Nakama Unity SDK, which can take a few minutes.
  2. Select Tools > Fusion > Fusion Hub > Welcome > Photon App Settings, and paste your App ID into the App Id Fusion field.
  3. Open the Assets/02_Platformer/02_Platformer.unity scene.

The scene contains a NakamaSingleton object that holds the Nakama connection settings. In the demo scene, they point to a server on Heroic Cloud. To use the server you started, change them to http, 127.0.0.1, port 7350, and server key defaultkey.

Play a game #

  1. Select Play, and start a game from the menu.
  2. In the Nakama console, go to Accounts. Your player appears in the list with a randomly generated username.

To play with a second player on the same computer, see Test multiplayer on one computer.

Authenticate players with Nakama #

Fusion connects players through Photon Cloud, which doesn’t know about your Nakama accounts. Custom authentication lets Photon Cloud ask your own server whether a player can connect. The player signs in to Nakama first, and the Fusion client passes their Nakama session token to Photon Cloud when it starts or joins a match. Photon Cloud then calls your Nakama server to check the token before it lets the player connect.

The flow has four steps:

  1. The player signs in to Nakama and receives a session token.
  2. The client passes the token to Fusion in the StartGame call.
  3. Photon Cloud sends the token to a Nakama RPC endpoint.
  4. The RPC validates the token and tells Photon Cloud whether to accept the player.

Only players with a valid Nakama session can join a match, and Photon Cloud learns who they are without handling a password.

Send the Nakama token to Fusion #

Add the session token as a custom authentication parameter named token in the AuthenticationValues you pass to StartGame:

UIGameMenu.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
var authentication = new AuthenticationValues
{
    AuthType = CustomAuthenticationType.Custom
};
authentication.AddAuthParameter("token", NakamaSingleton.Instance.Session.AuthToken);

var startArguments = new StartGameArgs()
{
    GameMode = Application.isEditor && ForceSinglePlayer ? GameMode.Single : GameMode.Shared,
    SessionName = string.IsNullOrEmpty(sessionName) ? RoomText.text : sessionName,
    PlayerCount = MaxPlayerCount,
    SessionProperties = new Dictionary<string, SessionProperty> { ["GameMode"] = GameModeIdentifier },
    Scene = sceneInfo,
    AuthValues = authentication
};

var startTask = _runnerInstance.StartGame(startArguments);

Photon Cloud appends each parameter to the URL it calls, so the server receives the token as the token query parameter. If the server rejects the token, StartGame fails and startTask.Result.ShutdownReason explains why.

Validate the token on the server #

Photon Cloud calls your server over HTTP, so there’s no Nakama session to authenticate it. Instead, the RPC reads the player’s token from the query string and validates it against the server’s session encryption key.

Register the RPC from InitModule:

main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
if err := registerAuth(initializer); err != nil {
		return err
	}
	logger.Info("Photon auth RPC loaded.")

    if err := initializer.RegisterBeforeUpdateAccount(func(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, in *api.UpdateAccountRequest) (*api.UpdateAccountRequest, error) {
		return nil, runtime.NewError("account updates are disabled", 7) // 7 = PERMISSION_DENIED
	}); err != nil {
		return err
	}

We make sure to hook into RegisterBeforeUpdateAccount and immediately return nil to prevent clients from updating their account data.

auth.go defines the RPC. It reads the token query parameter, then checks the token’s signature and expiry:

auth.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func photonAuth(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, payload string) (string, error) {
	params, _ := ctx.Value(runtime.RUNTIME_CTX_QUERY_PARAMS).(map[string][]string)
	paramKeys := make([]string, 0, len(params))
	for k := range params {
		paramKeys = append(paramKeys, k)
	}
	logger.Info("photon_auth: called, query params=%v, payload length=%d", paramKeys, len(payload))

	token := ""
	if values := params["token"]; len(values) > 0 {
		token = values[0]
	}
	logger.Info("photon_auth: token length=%d", len(token))

	if token == "" {
		return photonReply(photonAuthResponse{ResultCode: 2, Message: "token is required"})
	}

	_, username, _, _, _, _, ok := parseToken([]byte(CachedConfig.GetSession().GetEncryptionKey()), token, logger)
	if !ok {
		logger.Warn("photon_auth: rejected, failed to parse token")
		return photonReply(photonAuthResponse{ResultCode: 2, Message: "failed to parse token"})
	}

	logger.Info("photon_auth: success, username=%s", username)
	return photonReply(photonAuthResponse{ResultCode: 1, UserId: username})
}

Photon expects a JSON response. A ResultCode of 1 accepts the player, and 2 rejects them. On success, the UserId you return becomes the player’s user ID in Photon. The demo returns the Nakama username because it’s unique and matches the name friends search for.

Nakama session tokens are JSON Web Tokens (JWT) signed with the session.encryption_key setting, so the module can validate them without a database call. registerAuth stores the server’s configuration with initializer.GetConfig() so the RPC can read that key:

auth.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var CachedConfig runtime.Config

func registerAuth(initializer runtime.Initializer) error {
	var err error
	CachedConfig, err = initializer.GetConfig()
	if err != nil {
		return err
	}
	return initializer.RegisterRpc("photon_auth", photonAuth)
}

The parseToken function in auth.go does the validation. It accepts only HS256 signatures, requires an expiry, and rejects expired tokens. It decodes the token into a SessionTokenClaims struct that mirrors the claims in a Nakama session token. To reuse the validation in your own module, copy parseToken, SessionTokenClaims, and its methods from auth.go.

Never log the encryption key
Anyone with the session.encryption_key value can mint valid session tokens for any user. Don’t log it or the tokens you receive.

Point Photon at your server #

Register the RPC as the custom authentication provider for your Fusion app:

  1. In the Photon dashboard, open your Fusion app and go to its Authentication settings, then select CUSTOM SERVER.
  2. Set the Authentication URL to your RPC endpoint. For example, the demo uses https://nakama-photon-demo-c147.eu-west1-a.nakamacloud.io/v2/rpc/photon_auth.
  3. Add two key/value pairs:
    • http_key: <your-http-key>
    • unwrap: true
  4. Clear Allow anonymous clients to connect, independently of configured providers, and enable Reject all clients if not available.

The http_key parameter lets Photon Cloud make server-to-server calls to Nakama. Use your server’s runtime HTTP key. The unwrap parameter makes the RPC accept and return raw JSON, which is the format Photon expects.

Photon Cloud makes this request from the internet, so it can’t reach a Nakama server running on your computer. Use a Nakama server that Photon Cloud can reach, such as one on Heroic Cloud. The demo scene points to one for this reason.

Local testing
To set up custom authentication before you have a live server on Heroic Cloud, uncheck Reject all clients if not available in the Photon dashboard. Players can then connect when Photon Cloud can’t reach your server. To let players connect without a token at all, select Allow anonymous clients to connect, independently of configured providers.

To check that authentication works, start a game. Then remove the AddAuthParameter call and start another. The first game connects, and the second fails with an authentication error.

Use the Nakama username as the Fusion nickname #

Fusion needs a display name for each player, and the Nakama session already has one. When a player’s character spawns, Player.cs copies the Nakama username into a networked property, and Fusion sends it to every other client. Only the state authority can write a networked property, so the copy happens there:

Player.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
[Networked, HideInInspector, Capacity(24), OnChangedRender(nameof(OnNicknameChanged))]
public string Nickname { get; set; }

public override void Spawned()
{
    if (HasStateAuthority)
    {
        // ...
        Nickname = NakamaSingleton.Instance.Session.Username;
    }
    // ...
}

The menu also shows the username in its nickname field once sign-in succeeds:

UIGameMenu.cs
1
2
3
4
5
private void OnInstanceOnReceivedStartSuccess(ISession session)
{
    NicknameText.text = session.Username;
    NakamaSingleton.Instance.Socket.UpdateStatusAsync("In Menu");
}

The second line sets the player’s starting status, which the next section builds on.

Players see each other by their Nakama username, which is also the name friends search for to add them.

Publish the Fusion session name as a status #

Fusion players find each other by session name. Nakama status can carry that name to a player’s friends.

After StartGame succeeds, UIGameMenu publishes the session name with an In Game: prefix:

UIGameMenu.cs
1
2
3
4
5
6
7
8
var startTask = _runnerInstance.StartGame(startArguments);
await startTask;

if (startTask.Result.Ok)
{
    // ...
    await NakamaSingleton.Instance.Socket.UpdateStatusAsync($"In Game:{_runnerInstance.SessionInfo.Name}");
}

When the player disconnects or Fusion shuts down, UIGameMenu sets the status back to In Menu:

UIGameMenu.cs
1
2
3
await _runnerInstance.Shutdown();
// ...
await NakamaSingleton.Instance.Socket.UpdateStatusAsync("In Menu");

The friends list looks for this exact prefix, so it must match in both places. Join a friend’s session reads it back.

Join a friend’s session #

A player only receives the status of users they follow. For how following works, see Status and presence in the Unity client guide.

When the player signs in, FriendsList subscribes to ReceivedStatusPresence and loads the friends list. Each time the list loads, it follows every accepted friend and applies their current status:

FriendsList.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private async Task SyncFriendPresences()
{
    var socket = NakamaSingleton.Instance.Socket;
    if (socket == null) return;

    var friendIds = _friends
        .Where(x => x.State == (int)FriendState.Friend)
        .Select(x => x.User.Id)
        .ToList();
    if (friendIds.Count == 0) return;

    var result = await socket.FollowUsersAsync(friendIds);

    // Only online users are returned, so everyone missing from the result is offline.
    var online = new Dictionary<string, string>();
    foreach (var presence in result.Presences)
    {
        online[presence.UserId] = presence.Status;
    }

    foreach (var friendId in friendIds)
    {
        online.TryGetValue(friendId, out var status);
        ApplyStatus(friendId, status);
    }
}

The list reloads when a friend request is accepted, so new friends are followed straight away.

When a friend’s status starts with In Game:, FriendEntry takes the session name from it and shows a Join button:

FriendEntry.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
private const string InGamePrefix = "In Game:";

public void SetStatus(string newStatus)
{
    // ...
    if (_status.StartsWith(InGamePrefix))
    {
        if (_friendsList.gameMenu._runnerInstance == null)
        {
            _sessionName = _status.Substring(InGamePrefix.Length);
            joinGameButton.SetActive(true);
        }

        mutualStatusText.text = "In Game";
        return;
    }
    // ...
}

The Join button only appears while the player isn’t already in a session.

Selecting Join starts the Fusion game with the session name from the status. In shared mode, starting a game with an existing session name joins that session:

FriendsList.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public async Task JoinGame(string sessionName)
{
    if (_isJoining) return;

    _isJoining = true;
    // ...
    try
    {
        await gameMenu.StartGame(sessionName);
        friendsListGroup.gameObject.SetActive(false);
        await UpdateFriendsList();
    }
    finally
    {
        _isJoining = false;
        // ...
    }
}

Save the winner’s time #

Fusion decides who wins each round, and Nakama stores the winner’s time as a leaderboard score. GameManager measures time in Fusion ticks, and stores the start and end ticks in networked properties so every client sees the same values:

GameManager.cs
1
2
[Networked] public int MatchStartTick { get; set; }
[Networked] public int MatchEndTick { get; set; }

GameManager sets MatchStartTick when it spawns, and resets it at the start of each new round. In the first round, the clock starts when the first player joins, so the time can include waiting for others.

One client has state authority over GameManager, and that client decides the winner. When a player reaches the flag with enough coins, it sets Winner and MatchEndTick together. Winner is a networked property with a change callback, so OnWinnerChanged runs on every client when it changes. Each client checks whether it’s the winner, and only the winner’s client submits the time:

GameManager.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void OnWinnerChanged()
{
    if (Winner == PlayerRef.None || Winner != Runner.LocalPlayer)
        return;

    var ms = Mathf.RoundToInt((MatchEndTick - MatchStartTick) * Runner.DeltaTime * 1000f);
    _ = SubmitTimeAsync(ms);
}

private async Task SubmitTimeAsync(int timeMs)
{
    try
    {
        var nakama = NakamaSingleton.Instance;
        if (nakama?.Session == null) return; // Not signed in, nothing to submit.
        await nakama.Client.WriteLeaderboardRecordAsync(nakama.Session, NakamaSingleton.PlatformerLeaderboardId, timeMs);
    }
    catch (System.Exception e)
    {
        Debug.LogException(e);
    }
}

The winner’s client submits the time because WriteLeaderboardRecordAsync writes a record for the user who owns the session. No other client can write a record for the winner. For more on this call, see Submitting scores.

If the server rejects the time, SubmitTimeAsync logs the exception and the game keeps running.

To show the leaderboard in game, see Listing the top records. The demo does this in LeaderboardPanel.cs.

Because the client measures and submits its own time, a modified client can submit any time it wants. When to use an authoritative leaderboard covers this risk.

Set up the leaderboard on the server #

The server needs to do two things: create a leaderboard that accepts client writes, and reject times submitted by clients that can’t be real. The demo does both in leaderboard.go, which InitModule loads when Nakama starts:

main.go
1
2
3
4
if err := registerLeaderboard(ctx, logger, nk, initializer); err != nil {
		return err
	}
	logger.Info("Leaderboard module loaded.")

registerLeaderboard creates the leaderboard and registers the hook. For what each argument does, see Create a leaderboard.

leaderboard.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const (
	platformerBoard = "platformer_times"
	minPlausibleMs  = 3000 // Faster than this is not reachable, so reject it.
)

func registerLeaderboard(ctx context.Context, logger runtime.Logger, nk runtime.NakamaModule, initializer runtime.Initializer) error {
	if err := nk.LeaderboardCreate(ctx, platformerBoard, false, "asc", "best", "", nil, true); err != nil {
		logger.Warn("LeaderboardCreate: %v", err) // Also fires on restarts if it already exists.
	}
	return initializer.RegisterBeforeWriteLeaderboardRecord(beforeWriteLeaderboardRecord)
}

The demo creates the leaderboard with these settings:

  • false makes the leaderboard non-authoritative, so clients can write to it. The demo needs this because the winner’s client submits the time. See also: When to use an authoritative leaderboard.
  • "asc" with "best" keeps each player’s lowest time, because a lower time is better.
  • The final true turns on ranks, which a leaderboard screen can show next to each time.
Leaderboard settings can't change
Nakama can’t change a leaderboard’s settings after you create it. If you created platformer_times earlier with different settings, delete it in the console, or run docker compose down -v to reset the local database. Then restart the server so the module creates it again.

Since any client can write to the leaderboard, the before hook is the server’s way to check submitted times. It runs before Nakama saves any record a client writes. For platformer_times it rejects times under 3,000 milliseconds, which no player can reach in a real round:

leaderboard.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func beforeWriteLeaderboardRecord(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, in *api.WriteLeaderboardRecordRequest) (*api.WriteLeaderboardRecordRequest, error) {
	if in.GetLeaderboardId() != platformerBoard {
		return in, nil
	}
	if in.GetRecord().GetScore() < minPlausibleMs {
		return nil, runtime.NewError("time not plausible", 3)
	}
    in.GetRecord().Operator = api.Operator_BEST // Make sure that players can't change the operator in their request.
	return in, nil
}

Returning the request lets Nakama save the record. Returning an error rejects it, and the client’s WriteLeaderboardRecordAsync call throws. For more on guarding client calls, see How to restrict access to Nakama APIs.

After you change the module, rebuild and restart the server with docker compose up --build. The logs show Leaderboard module loaded. when the module is ready.

When to use an authoritative leaderboard #

The before hook catches impossible times, but it can’t tell a real time from a made-up one. A player who modifies their client can submit exactly 3,000 milliseconds and take first place.

A non-authoritative leaderboard accepts that risk to keep things simple: the client writes its own record, and the server doesn’t need to know anything about the match. That’s a reasonable trade-off for a demo or a casual game, where a cheated score doesn’t cost anyone anything.

An authoritative leaderboard only accepts records the server writes, so clients can’t submit scores at all. Use one when scores matter, for example when they decide rewards or a ranking that players compete for. To make the demo’s leaderboard authoritative:

  1. Delete the existing platformer_times leaderboard in the console.
  2. Create the leaderboard with authoritative set to true.
  3. Remove the client’s WriteLeaderboardRecordAsync call.
  4. Write records from the server with nk.LeaderboardRecordWrite.

An authoritative leaderboard only helps if the server knows the real time when scores are submitted. In shared mode, the session runs in Photon Cloud without a game server, and Nakama doesn’t see the match either, so scoring depends on clients to report results. To make results harder to fake:

  • Compare reports from every client: Have every player’s client report the result, and only save the record when all the reports agree. This way a single modified client can’t change the result on its own. Plan for the edge cases, such as a round with only one player, so that honest scores aren’t discarded unnecessarily.
  • Check results on Photon’s servers: Run a custom Photon plugin that validates results inside the session before they reach Nakama. Custom plugins are only available on Photon Enterprise Cloud, so contact Photon to set one up.

For full control, use one of Fusion’s other topologies, where a dedicated server decides the outcome and can report it to Nakama.

Test multiplayer on one computer #

To test friends and joining matches, you need two players signed in to different Nakama accounts. The demo signs each player in with a device ID it stores in PlayerPrefs, and the Unity Editor and a standalone build keep separate PlayerPrefs. Use the Editor as Player 1 and a standalone build as Player 2.

Build and launch both players #

  1. Go to Edit > Project Settings > Player. Under Resolution and Presentation, enable Run In Background, and set Fullscreen Mode to Windowed. Without Run In Background, the window you aren’t using pauses, and Fusion disconnects it.
  2. Go to File > Build Profiles. Make sure the game scene is in the scene list, and select Build.
  3. In the Editor, select Play. This is Player 1.
  4. Launch the build. This is Player 2.
  5. Open the Nakama console, go to Accounts, and confirm that it lists two users.
The Nakama console showing all the players that signed in
Once you've signed in multiple players you can see them listed in the Nakama console.

Play a round #

  1. Use the friends list to make Player 1 and Player 2 friends.
  2. As Player 1, start a game.
  3. As Player 2, check that Player 1 shows as In Game, with a Join button.
  4. Select Join. Both players are now in the same Fusion session.
  5. Play a round until one player wins.
  6. Open the leaderboard. It shows a row with the winner’s username and time.
The in-game leaderboard showing the winning players and their times
The winner's time in the leaderboard.

To check the record on the server, open the Nakama console, go to Leaderboards, and select platformer_times. Then have the same player win another round faster. Because the leaderboard uses the best operator, a faster time replaces the record and a slower time leaves it unchanged.

Conclusion #

You’ve now seen how Photon Fusion and Nakama work together to give players an identity, friends, and scores that last beyond a single match:

  • Authentication: Photon Cloud checks each player’s Nakama session token through a custom authentication RPC, and the Nakama username becomes the player’s Fusion nickname.
  • Friends: Nakama status carries the Fusion session name, so friends can join each other’s matches from the friends list.
  • Leaderboards: The winner’s client saves their time to a Nakama leaderboard, and a before hook rejects times that are too fast to be real.

To go further, try showing only friends’ times on the leaderboard, or move scoring to an authoritative leaderboard if scores need to be protected from modified clients.

See also #