Leaderboards step by step
This guide takes you from "no leaderboard" to a working weekly board in six steps: choose the rules, set them in the console, submit scores from the game or your server, show ranks and test. The leaderboards reference has the full contract. Examples assume const SDK = window.ZokoGames.SDK; and await SDK.init(); as in the SDK introduction; unfamiliar terms are in the glossary.
1. Decide what the board measures#
| You want to rank | Sorting | Incremental | Label |
|---|---|---|---|
| Best single score | Highest first (DESC) |
Off | POINTS or XP |
| Fastest time | Lowest first (ASC) |
Off | MINUTES |
| Total progress this week | Highest first | On: each submission adds to the weekly total | XP |
Boards reset every week (Monday 09:00 UTC). At the end of the week, ranks 1 to 3 earn gold, silver and bronze trophies on their profile; with at least 10 players, the top 1 %, 5 % and 10 % earn trophies too.
2. Configure it in the console#
Open the game's Leaderboard tab. It holds the one switch, Leaderboard enabled: turn it on, set the rules and press Save rules (the Technical step only shows whether the leaderboard is on and links here). Only studio admins and owners can change it. Keys are opt-in. Without an Encryption key the board accepts plain scores, which anyone can forge; press Generate next to it to accept only encrypted scores from then on. Generate a Server API key only if your own server submits scores. Keys can be generated once the rules are saved, and creating, rotating or revoking one asks for a second step (a passkey or an authenticator app on your player account; add one first in the account's security settings). Generate the encryption key before you launch: on a live game the first key makes the board ignore the plain scores of the build players already have. A new key is shown once; copy it immediately. Rotating the encryption key breaks builds that still use the old one.
- Set the minimum and maximum to values a legitimate player can reach. Anything outside is dropped. On an incremental board the range applies to each submitted amount, not to the total.
- Set a cooldown to stop spam submissions (for example 10 seconds).
- Write a one-line player guide that tells players how to score.
3. Submit from the game (client)#
const KEY = "<encryption key from the console>";
const GAME_ID = "<your game id>"; // the id in your console address: /developer/games/<id>. Anything in a browser can be read; see the warning below
async function encryptScore(score, keyBase64, userId, gameId) {
const raw = Uint8Array.from(atob(keyBase64), (c) => c.charCodeAt(0));
const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, ["encrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(12));
const additionalData = new TextEncoder().encode(`zoko-score-v1|${userId}|${gameId}`); // binds the payload to this player and game
const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData }, key, new TextEncoder().encode(`${score}|${Date.now()}`)));
const out = new Uint8Array(iv.length + sealed.length);
out.set(iv, 0);
out.set(sealed, iv.length);
return btoa(String.fromCharCode(...out));
}
async function finishRun(score) {
const user = await SDK.user.getUser();
if (!user) return; // guests do not appear on boards
await SDK.user.submitScore({ encryptedScore: await encryptScore(score, KEY, user.__dangerousUserId, GAME_ID), score });
}Encrypt at the moment you submit: payloads are bound to the player and game, expire after 2 minutes and work once. Submit once per run, at the end. The call resolves (with no value) whether or not the score was accepted, so do not treat it as a confirmation; the portal shows the player a rank toast when it was. The one rejection to handle is rateLimited, thrown when a player goes past 30 submissions per minute per game. A guest's submission records nothing; when the score would reach the top 10 of the current week's board, the portal invites them to sign in, at most once per game per page view. A run that does not place does not use up that invitation. Offline players cannot submit: the call needs the portal (see offline play).
The client path stops casual tampering, not a determined cheater, because the key ships in the browser. For competitive games compute the score on your server and use the server API.
Submit once per finished run#
Our own games submit through one small shared helper. The sketch below keeps its rules and leaves out the rest: detect the feature first, submit once per run, never for a child, never a value the board would drop, and keep a guest's score until they sign in.
// Uses KEY, GAME_ID and encryptScore() from the example above. Set KEY to "" when the board has no encryption key.
const RANGE = { min: 1, max: 300 }; // the same min and max as on the Leaderboard tab
const handled = new Set(); // ids of runs already submitted or skipped
let kept = null; // best score of a signed-out player, sent after sign-in
function boardAvailable() {
if (SDK.environment === "disabled" || typeof SDK.user.submitScore !== "function") return false;
if (!SDK.user.isUserAccountAvailable) return false;
const s = SDK.game.settings;
return !(s.kidsMode ?? s.disableChat); // kids mode: no boards
}
async function send(user, score) {
const encryptedScore = KEY ? await encryptScore(score, KEY, user.__dangerousUserId, GAME_ID) : "";
try {
await SDK.user.submitScore({ encryptedScore, score });
return "sent"; // delivered; the portal shows the rank toast if it counted
} catch (e) {
return e?.code === "rateLimited" ? "too-fast" : "error";
}
}
async function onRunFinished(runId, score) {
if (handled.has(runId) || !boardAvailable()) return "off";
handled.add(runId);
if (!Number.isFinite(score) || score < RANGE.min || score > RANGE.max) return "out-of-range";
const user = await SDK.user.getUser();
if (user) return send(user, score);
kept = kept === null ? score : Math.max(kept, score); // highest-first board: keep the better run
return "guest"; // show a "Sign in to rank" button
}
async function onSignInClicked() {
const user = await SDK.user.showAuthPrompt().catch(() => null);
if (!user || kept === null) return;
const score = kept;
kept = null;
await send(user, score);
}- Detect the feature. Show no board UI when the SDK is disabled, when the host has no player accounts (
isUserAccountAvailableisfalse) or whensubmitScoreis missing. - Once per run. Key each submission by a run id, so a second game-over screen or a double tap cannot send the same run twice. More than 30 calls a minute per player and game (10 on a board without an encryption key) reject with
rateLimited. - When
rateLimitedhappens. Nothing was recorded, so the run is still worth sending: keep the score (not the payload), wait about a minute, encrypt it again and send one score for the backlog, when the sketch returns"too-fast". A retry that lands after Monday 09:00 UTC counts for the new week. The full retry rule is in the leaderboards reference, under Client submission. - Guests. The SDK does not check whether the player is signed in: it passes the call to the portal. For a signed-out player the portal records nothing and resolves the call; when the score would reach the top 10 of the current week's board it also invites the player to sign in, at most once per game per page view. The sketch checks
getUser()first instead, keeps the guest's best run and sends it onceshowAuthPrompt()resolves with a player. On an incremental board, add the kept runs up instead of keeping the best one. - Offline. A run that ends offline records nothing unless you also pass
delayed(SDK 1.6.4): a copy sealed at the end of the run withearnedAt = Date.now(). The portal keeps it on the device for a signed-in player and sends it when they are back online, within 72 hours; it counts for the all-time board only, not the weekly board. How to seal it: Offline scores. Withoutdelayed, an offline score is not queued. - Kids mode. There are no boards: the portal records nothing and shows no sign-in prompt,
getUser()resolvesnull, and the server API answers403kids-gamefor a game with the kids flag. Hide the board UI. - Range and cooldown. Set the min, max and cooldown on the Leaderboard tab. The portal enforces them and drops a value outside the range, or one sent inside the cooldown, without telling the game. Checking the range in the game only saves a pointless call. On an incremental board the range applies to each run's amount.
- No confirmation.
submitScoreresolves with no value whether or not the score counted; the portal shows the rank toast when it did. Treat"sent"as delivered, not as ranked.
What the encryption key protects#
With a key, the portal accepts only a payload encrypted with it, made for this player and this game, less than 2 minutes old and not seen before. That stops a number typed into the browser's developer tools, a payload copied from another player or game, and an old payload sent again. It does not stop a player who reads the key from your game's files (everything shipped to a browser can be read) and encrypts any score they like, and a board without a key accepts the plain number. When scores matter, compute or check them on your server and submit them with the server API key (step 4): that key never leaves your server, and the server API answers with explicit errors, for example 403 developer-suspended while your studio is suspended. Every code is listed in the leaderboards reference.
4. Submit from your server (authoritative)#
- The game sends
await SDK.user.getUserToken()with the run to your server. - Your server verifies the token against the JWKS, checks the
gameIdclaim and takesuserId. - Your server validates the run and posts the score:
const res = await fetch("https://www.zokogames.com/api/v1/leaderboard/scores", {
method: "POST",
headers: { "x-api-key": process.env.ZOKO_LEADERBOARD_KEY, "content-type": "application/json" },
body: JSON.stringify({ scores: [{ userId, score }] }),
});
const { ok, results } = await res.json(); // results[i].ok, .rank, .score or .errorBatch up to 100 scores per request (more is rejected with too-many-items). The API key must never be shipped in the game.
5. Show it to players#
The portal already shows the leaderboard next to the game and refreshes the player's rank after an accepted submission, so you may not need anything else. To show ranks inside your own UI, read the public endpoint. A game on its own origin (https://g-<slug>.zokogames.com) can call it directly from the browser: the endpoint answers CORS for game origins and the portal only, without credentials, so the player's session is not sent and me is empty. You can also call it from your server.
// in the game, or on your server (Node 20+)
const r = await fetch(`https://www.zokogames.com/api/leaderboard/${GAME_ID}?scope=global&limit=10`);
const { entries, me, neighbours, season, seasonEndsAt } = await r.json();Without a session (a server call, or a browser call without credentials) there is no signed-in player, so me is empty and scope=friends answers 401. Cache the answer for a short time instead of calling per player.
6. Test#
- Local mode accepts
submitScoreand records nothing: it has no board. It logs one console line per call, and offline (?offline=true) with a signed-in player anddelayedit shows "Score saved offline". Use the Preview tool to confirm the call is made ("A leaderboard score was submitted" in the game's preview checklist), and test acceptance on a build in basic launch with a real account. - If scores seem to vanish, check in this order: the player is signed in, the board is enabled, the value is inside min and max, the cooldown has passed, the key in the build matches the console key.