Player accounts and your backend
This guide shows how to read who is playing, offer sign-in, send a verified identity to your own backend and link an existing game account, with the minimum code for each account scenario. Players are either signed in to ZokoGames or guests, and your game must work for both. Examples assume const SDK = window.ZokoGames.SDK; as in the SDK introduction; terms such as guest and token are in the glossary.
1. Show who is playing#
await SDK.init();
const user = await SDK.user.getUser(); // null for guests
if (user) hud.setName(user.username, user.profilePictureUrl);
SDK.user.addAuthListener((u) => hud.setName(u.username, u.profilePictureUrl));The auth listener also fires when the player signs in through the portal's own header while your game is open. getUser() is asynchronous and resolves null for a guest. When the player signs out, the portal restarts your game as a guest.
What you see in other situations: offline, the player is the last one signed in on this device, or a guest. In kids mode there is no sign-in at all (showAuthPrompt ends as userCancelled). In local mode (your own localhost page) the player is a fake user1 unless you use the switches in step 5.
2. Offer sign-in on a player action#
if (SDK.user.isUserAccountAvailable && !user) signInButton.hidden = false;
signInButton.onclick = async () => {
try { await SDK.user.showAuthPrompt(); }
catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};Never open the prompt automatically at start.
3. Send a verified identity to your server#
The browser can lie about __dangerousUserId; a token cannot be forged.
async function callBackend(path, body) {
let token = null;
try { token = await SDK.user.getUserToken(); } catch (e) { /* userNotAuthenticated: guest */ }
return fetch("https://api.example.com" + path, {
method: "POST",
headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: JSON.stringify(body),
});
}On the server, verify the signature with the portal's public keys, check expiry and check that gameId equals your game's id. A complete verifier in Node.js, Python and C# is in the user module reference. Express middleware:
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));
export async function zokoAuth(req, res, next) {
const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
if (!raw) { req.player = null; return next(); } // guest
try {
const { payload } = await jwtVerify(raw, JWKS, {
algorithms: ["RS256"],
issuer: "zokogames",
audience: process.env.ZOKO_GAME_ID,
clockTolerance: 5,
});
if (payload.gameId !== process.env.ZOKO_GAME_ID) throw new Error("wrong game");
req.player = { id: payload.userId, name: payload.username };
next();
} catch {
res.status(401).json({ error: "invalid_token" });
}
}Tokens last one hour and carry userId, gameId, username, profilePictureUrl. The SDK caches a token until a minute before it expires, so call getUserToken() before every backend request. Local mode issues unsigned tokens that a correct verifier rejects.
To submit scores for the weekly leaderboard from the same token, see leaderboards step by step.
4. Link an existing game account (full integration)#
async function onSignedIn() {
const { linked } = await (await callBackend("/session", {})).json();
if (linked) return; // userId already linked: load that account
const { response } = await SDK.user.showAccountLinkPrompt();
if (response === "yes") await callBackend("/link", {}); // server links the verified userId to this game account
}Prefer linking to a fresh account over merging two accounts that both have progress, and always treat the verified userId as the key. A complete walkthrough with a server-side example is in account linking step by step.
5. Test every path locally#
| Path | URL switch |
|---|---|
| Guest | ?user_response=logged_out |
| Signed-in at start | ?user_response=user1 |
| Sign in on a button | ?user_response=logged_out&show_auth_prompt_response=user2 |
| Player cancels | ?show_auth_prompt_response=user_cancelled |
| Link accepted / declined | ?link_account_response=yes / no |
| Token fails / expired | ?token_response=logged_out / expired_token |
| No accounts at all | ?user_account_available=false |