OneLeader

Guide · Phaser 3 and 4

Add an online leaderboard to a Phaser game

Give your Phaser game a global high-score table in about ten minutes, with no server of your own. Players don't need an account: each one is an anonymous player remembered in the browser.

By the end, your game-over scene saves the score, tells the player their all-time rank and shows the top 10, with their own row highlighted.

1. Set up the leaderboard

  1. Sign in to the dashboard with GitHub or Google and create an app for your game. The free plan covers 10,000 scores a month.
  2. Under API keys, create a publishable key (lb_pk_…). It's safe to ship in the game.
  3. Under Allowed origins, add your dev server's origin (the address it prints, for example http://localhost:8080) and the origin you'll publish to, such as your itch.io or own domain. Other origins get 403.
  4. Under Metrics, create highscore with the aggregation max, so each player keeps their best run.
  5. Under Leaderboards, create alltime on highscore, ranked highest first.

2. Install the SDK

In your Phaser project (for example one made from Phaser's Vite template):

npm i @oneleader/sdk

3. Add a leaderboard module

Save this as src/leaderboard.ts and paste in your publishable key. It keeps Phaser out of the network code, and if the leaderboard can't be reached (offline, over quota, rate limited) it returns null so the game carries on.

import { createClient, OneLeaderError, type Rankings } from "@oneleader/sdk";

const SESSION = "oneleader-session";
const saved = localStorage.getItem(SESSION);
const client = createClient({ publishableKey: "lb_pk_...", session: saved ? JSON.parse(saved) : undefined });

// The leaderboard is a bonus: offline, over quota or rate limited, the game carries on without it.
const unavailable = (e: unknown) => e instanceof OneLeaderError || e instanceof TypeError;

/** First run only: start an anonymous player and ask for the name shown on the board. */
async function ready() {
  if (localStorage.getItem(SESSION)) return;
  localStorage.setItem(SESSION, JSON.stringify(await client.startSession()));
  const name = prompt("Your name for the leaderboard?")?.trim();
  if (name) await client.setDisplayName(name).catch(() => {}); // a rejected name (e.g. too long) leaves the player "Anonymous"
}

/** Records a finished run. Returns the player's all-time rank (by their best score), or null if it couldn't be saved. */
export async function submitRun(score: number): Promise<number | null> {
  try {
    await ready();
    const receipt = await client.submitScore("highscore", score);
    return receipt.leaderboards.find((b) => b.key === "alltime")?.rank ?? null;
  } catch (e) {
    if (unavailable(e)) return null;
    throw e;
  }
}

/** The top 10, plus the player's own row in `user` even when they're further down. */
export async function topTen(): Promise<Rankings | null> {
  try {
    return await client.getLeaderboard("alltime", { limit: 10 });
  } catch (e) {
    if (unavailable(e)) return null;
    throw e;
  }
}

The first time a player finishes a run, prompt() asks for their name. That's enough to get going; swap it for your own name-entry screen later and call setDisplayName from there.

4. Show it on game over

Add a GameOver scene to your game config's scene list, and start it from your game scene when the run ends:

this.scene.start("GameOver", { score: this.score });

The scene draws straight away, then fills in the rank and the table once they arrive:

import Phaser from "phaser";
import { submitRun, topTen } from "./leaderboard";

export class GameOver extends Phaser.Scene {
  constructor() {
    super("GameOver");
  }

  // Start it from your game scene with: this.scene.start("GameOver", { score });
  create({ score }: { score: number }) {
    const x = this.scale.width / 2;
    this.add.text(x, 60, `Score: ${score}`, { fontSize: "32px" }).setOrigin(0.5);
    const status = this.add.text(x, 105, "Saving your score…", { fontSize: "18px" }).setOrigin(0.5);
    this.add.text(x, this.scale.height - 40, "Press SPACE to play again", { fontSize: "16px" }).setOrigin(0.5);
    this.input.keyboard?.once("keydown-SPACE", () => this.scene.start("Game"));
    this.showBoard(score, status, x);
  }

  private async showBoard(score: number, status: Phaser.GameObjects.Text, x: number) {
    let left = false;
    this.events.once("shutdown", () => (left = true));
    const rank = await submitRun(score);
    const board = await topTen();
    if (left) return; // the player restarted before the board loaded

    status.setText(rank ? `Your best is #${rank} all time` : "Leaderboard unavailable right now");
    board?.rankings.forEach((row, i) => {
      const me = row.player_id === board.user?.player_id;
      this.add
        .text(x, 150 + i * 28, `${row.rank}. ${row.display_name ?? "Anonymous"}   ${row.value}`, { fontSize: "18px", color: me ? "#30b0c7" : "#ffffff" })
        .setOrigin(0.5);
    });
  }
}

Phaser draws display names as canvas text, not HTML, so whatever a player types can't inject markup into your page.

5. Try it

Run the game, finish a run and you should see yourself at #1. Open it in a private window to play as a second player. If the status says the leaderboard is unavailable, check the browser console: a 403 means the page's origin isn't in Allowed origins, and a 404 means the metric or leaderboard key doesn't match.

Next steps