# Add Nakama to a Photon Fusion game

**URL:** https://heroiclabs.com/docs/nakama/guides/concepts/photon-integration/
**Summary:** See how a Photon Fusion game uses Nakama to sign players in, let friends join each other's matches, and save the winner's time to a leaderboard.
**Keywords:** photon, photon fusion, photon integration, fusion, multiplayer
**Categories:** nakama, photon-integration, concepts

---


# 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](https://github.com/heroiclabs/nakama-photon-demo), which adds Nakama to Photon's [Fusion Starter](https://doc.photonengine.com/fusion/v2/game-samples/fusion-starter/overview) 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](https://heroiclabs.com/docs/images/pages/nakama/guides/concepts/nakama-photon/photon-sample_hu1098696454218645586.webp)

*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](/docs/sample-projects/games/nakama-photon/).

## 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.](https://heroiclabs.com/docs/images/pages/nakama/guides/concepts/nakama-photon/photon-nakama-sequence.2c3febe500212227eff0db474830fabf75e5c1382d516cbe63136ba5d9c21c4d.svg)

## 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](/docs/nakama/concepts/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](/docs/nakama/concepts/authentication/), [friends](/docs/nakama/concepts/friends/), and [leaderboards](/docs/nakama/concepts/leaderboards/). Clone the [demo project](https://github.com/heroiclabs/nakama-photon-demo) 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:

- [Install Nakama with Docker Compose](/docs/nakama/getting-started/install/docker/): Run a Nakama server on your computer.
- [Nakama Unity client guide](/docs/nakama/client-libraries/unity/#installation): Install the client and connect to Nakama.
- [Go runtime](/docs/nakama/server-framework/go-runtime/): Write server modules that register functions and hooks in `InitModule`.
- [Fusion 2 introduction](https://doc.photonengine.com/fusion/v2/fusion-intro): Learn how Fusion syncs game state, including in shared mode.

## Run the demo

To run the demo locally and change it, you need [Unity 6](https://unity.com/releases/editor/archive), [Docker Desktop](https://www.docker.com/products/docker-desktop/), and a free [Photon account](https://dashboard.photonengine.com/) 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](/docs/nakama/getting-started/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](#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](https://doc.photonengine.com/fusion/v2/manual/connection-and-matchmaking/authentication/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](/docs/nakama/server-framework/introduction/#rpc-functions) 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**

```csharp
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**

```go
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**

```go
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**

```go
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](https://dashboard.photonengine.com/), 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](/docs/nakama/server-framework/runtime-examples/server-to-server/) calls to Nakama. Use your server's [runtime HTTP key](/docs/nakama/getting-started/configuration/#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](https://heroiclabs.com/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**

```csharp
[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**

```csharp
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](/docs/nakama/concepts/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**

```csharp
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**

```csharp
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](#join-a-friends-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](/docs/nakama/client-libraries/unity/#status--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**

```csharp
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**

```csharp
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**

```csharp
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**

```csharp
[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**

```csharp
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](/docs/nakama/client-libraries/unity/#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](/docs/nakama/client-libraries/unity/#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](#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**

```go
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](/docs/nakama/concepts/leaderboards/#create-a-leaderboard).

**leaderboard.go**

```go
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](#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](/docs/nakama/server-framework/introduction/hooks/) 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**

```go
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](/docs/nakama/guides/server-framework/guarding-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](https://www.photonengine.com/contact) 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](https://heroiclabs.com/docs/images/pages/nakama/guides/concepts/nakama-photon/nakama-console_hu2845921351942497641.webp)

*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](https://heroiclabs.com/docs/images/pages/nakama/guides/concepts/nakama-photon/photon-leaderboard_hu2573990737303510996.webp)

*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

- [Nakama and Photon Fusion demo](https://github.com/heroiclabs/nakama-photon-demo)
- [Nakama Unity client guide](/docs/nakama/client-libraries/unity/)
- [Leaderboards](/docs/nakama/concepts/leaderboards/)
- [Status and presence](/docs/nakama/concepts/status/)
- [Friends](/docs/nakama/concepts/friends/)
- [Go runtime](/docs/nakama/server-framework/go-runtime/)
- [Hooks](/docs/nakama/server-framework/introduction/hooks/)
- [Photon Fusion custom authentication](https://doc.photonengine.com/fusion/v2/manual/connection-and-matchmaking/authentication/custom-authentication)
- [Photon Fusion documentation](https://doc.photonengine.com/fusion)
