Players & worlds
Every Unbase project includes an online layer for browser games, next to Leaderboards. A static game (itch.io, your own site, GitHub Pages…) gets, with the anon key and no backend of its own:
- players: a lasting anonymous id per device, a display name, and more devices linked with the same save codes leaderboards use,
- cloud saves: one versioned JSON blob per player, which an old device can't overwrite, and which friends can visit,
- a world claims registry: an endless grid of cells (levels, islands, archipelagos…) handed out on a spiral from
0,0, one decision point so two players can't win the same cell, - neighbourhoods: one shared grid where every player has a home square, placed so nobody has more than 4 neighbours, with moves next to friends,
- a public world map, friend codes, mailboxes (gifts, bottles, guestbook entries) and scoped leaderboards (
beam:3,-2).
The server never stores your world: if your game generates a cell from its coordinates, all Unbase keeps is who holds it.
Who can do what
| Caller | Sends | Can |
|---|---|---|
| Anyone with the anon key | apikey: <anon key> |
Create or sign in a player. Read public profiles, the map, claims, and saves whose owner allows visits. |
| A player | apikey + Authorization: Bearer <player token> |
Everything above, plus write their own rows: profile, save, claims, friends and mailbox. |
| You, the project owner | apikey: <secret key> |
Read mail reports and mute players. Skips the origin allowlist. |
There is no route that writes another player's rows: every write goes to the player the token belongs to, so the anon key alone can't change anyone's data. The origin allowlist from your leaderboard config (including the itch keyword) applies to every route here.
Base URL: https://api.unbase.dev/v1/projects/:id. Errors use the usual { "error": { "code", "message" } } body.
Quick start
const API = "https://api.unbase.dev/v1/projects/YOUR_PROJECT_ID";
const KEY = "YOUR_ANON_KEY";
async function api(method, path, body) {
const headers = { apikey: KEY, "content-type": "application/json" };
const token = localStorage.getItem("player-token");
if (token) headers.authorization = "Bearer " + token;
const res = await fetch(API + path, { method, headers, body: body && JSON.stringify(body) });
return { status: res.status, ...(await res.json()) };
}
// 1. Sign in (creates the player the first time).
const { player, token } = await api("POST", "/players", { name: "Wren" });
localStorage.setItem("player-token", token);
// 2. Claim an archipelago.
const claim = await api("POST", "/claims/next");
startGame(claim.archipelago); // e.g. "1,-1"
// 3. Save on meaningful events.
let version = player.save ? player.save.version : 0;
async function save(state) {
const res = await api("PUT", "/players/me/save", { version, data: state });
if (res.status === 409) return reloadNewerSave(res.error.currentVersion);
version = res.version;
}
Players
POST /players{ name?, device? }signs a device in and returns{ created, player, token, device }(201when the player is new).- With no
device, it creates a new player with a fresh random device id. - With a
device(at least 16 random characters), it returns that device's player, creating it the first time, with a new token. So a game that loses its storage gets the same player back on every load. Use the id the leaderboard SDK already keeps (await UnbaseLeaderboard.ready()), which survives in a partitioned cookie on itch.io even whenlocalStorageis blocked. Treat a device id like a password: whoever has it can sign in as that player. - Each sign-in issues a token. A player keeps their 20 newest tokens; older ones stop working.
- Creating new players is limited to 60 per IP per hour (
429withRetry-After); signing an existing device back in isn't.
- With no
GET /players/mereturns your own view:{ id, name, friendCode, visits, mail, home, save: { version, updatedAt } | null, createdAt }.homeis your active claim, else the one you finished last.PATCH /players/me{ name?, visits?, mail? }:visits: who can read your save."public"(anyone),"friends"(default) or"private".mail: who can message you."anyone"(default),"friends"or"off".- Renaming also renames you on the map.
GET /players/:playerIdreturns the public view:{ id, name, visits, home, createdAt }.POST /players/me/pingis a heartbeat that keeps your claim from going idle. Saving does this too.
More devices: save codes
POST /players/me/link-code→{ code: "XXXX-XXXX", expiresAt }. The code is single-use and lasts 15 minutes. Limited to 5 per hour.- On the other device:
POST /players/link{ code }→{ player, token, device }. Store the token and adopt thedeviceid (for leaderboards too). Limited to 10 attempts per IP per hour.
These are the same codes as the leaderboard SDK's linkCode(), so a code from either one signs the new device in to both.
More devices: email
A player can attach an email, then load the same player on any device by typing a 6-digit code sent to it. It uses codes, not links, because games often run in an iframe (itch.io) that a link can't open back into.
POST /players/me/email{ email }emails a 6-digit code to that address →{ sent, email }. A new request replaces the last one. Limited to 5 per player per hour, and 5 codes per address per hour.POST /players/me/email/verify{ code }→{ player }, now withemailset.409 email_in_useif another player already has that address (sign in with it instead). Attaching a new address replaces the old one.DELETE /players/me/emaildetaches it →{ player }.GET /players/meshows youremail(ornull). Nobody else sees it.- On another device:
POST /players/email{ email }emails a sign-in code if a player has that address. It answers{ sent: true }either way, so it can't be used to find out who plays. Limited to 20 per IP per hour. - Then
POST /players/email/verify{ email, code }→{ player, token, device }, likePOST /players/link: store the token and adopt thedeviceid. - Codes are single-use, last 15 minutes, and stop working after 5 wrong guesses (
400 bad_code). - Without a Resend key (local dev), nothing is emailed and the response carries
devCodeinstead. - The emails come from your game's name, set under Settings → Game name in the dashboard (or
"gameName"in the game config,PUT /leaderboards/config):Palafita <no-reply@unbase.dev>, subject "Your Palafita code: 123456". Up to 40 characters, no quotes or angle brackets. Without one they come from "Unbase Games".
Keeping a value in the browser's cache (experimental)
Safari, Brave and every iPhone browser give a game inside another site's frame (itch.io) storage that lives in memory only. GET /v1/keep/<projectId>/<slot> lets a game park a small value (up to 600 URL-safe characters, such as its device id and token) in the browser's HTTP cache instead:
- Write:
fetch(url, { cache: "reload", headers: { "x-unbase-keep": value } })answers the value back, cacheable for a year. - Read:
fetch(url, { cache: "force-cache" })returns it from the cache without reaching the server;204means the cache had nothing. - Nothing is stored on the server. Browsers can clear their cache at any time, so treat it as a hint and keep email as the way back. Only do it when the player asks to be remembered.
Cloud saves
One save per player: any JSON up to 256 KB, stored in R2. Saves share the project's file-storage quota with uploaded files.
PUT /players/me/save{ version, data }.versionis the version this save is based on:0for the first save, then the version the last read or write returned.200 { version, updatedAt, size }when it was the latest. The new version isversion + 1.409 save_conflictwhen the stored save is newer (another device saved in between). The error body also hascurrentVersionandupdatedAt, so the game can load the newer save, merge, and write again.- If two devices write from the same version at the same time, exactly one wins.
GET /players/me/save→{ playerId, version, updatedAt, data }. Add?since=<version>to get{ …, unchanged: true }with nodatawhen there's nothing newer, which is a cheap check on startup.GET /players/:playerId/save(optionally with your token) reads someone else's save if theirvisitssetting allows you. Otherwise you get403 visits_not_allowed.404 no_savemeans they haven't saved yet.
Save on meaningful events (a relic, a build, landing, sleeping), not on a timer. Each save is one R2 write and a few rows.
Backups
When a save is replaced, the old one is kept as a backup if the player has no backup from the last 6 hours, or if the new save is a third smaller or more (what a fresh game uploaded over a real one looks like). Up to 6 backups per player, each kept for 7 days. They count against the file-storage quota.
GET /players/:playerId/save/backups(secret key) →{ current, backups: [{ version, savedAt, size, reason }] }, newest first.POST /players/:playerId/save/restore{ version }(secret key) makes that backup the save again, as a new version, so every device sees it as newer. The save it replaced becomes a backup, so a restore can be undone.
Claims registry
The world is an endless grid of cells named "x,y" (integers within ±1,000,000). All claims for a project are decided by one Durable Object, one at a time, so there are no races.
Every claim call answers with the same shape:
{
"archipelago": "1,0",
"claim": { "archipelago": "1,0", "x": 1, "y": 0, "status": "active", "owner": { "id": "p_…", "name": "Wren" }, "claimedAt": 1760000000000, "completedAt": null },
"requested": "5,5",
"granted": false,
"reason": "taken"
}
archipelago is always the cell the player holds now. granted says whether that's what they asked for; if not, reason says why:
| reason | meaning |
|---|---|
null |
You got what you asked for. |
"taken" |
Someone else holds the cell you asked for, so you got the next free one. Move the player there. |
"has_active_claim" |
You already hold an unfinished cell (this one). Complete or release it first. |
Routes (all need the player token except reading a cell):
POST /claims/next{ near? }hands out the next uncharted cell on a square spiral out from0,0, reusing released cells first. Withnear: "<friend code>", it lands next to that friend's home instead (within 6 rings, falling back to the spiral). Witharound: "<cell>"andring: n, it lands on a random free cell exactlynrings from that cell, or the next ring out once that one is full: every new player starts about the same distance from a shared centre, spread all the way round it (ringis 0 to 256;nearwins when both are given). Calling it again while you hold an unfinished cell returns that cell, so it's safe to retry.POST /claims/:cell{ near?, around?, ring? }claims a specific cell, e.g. one the game already started offline. If it's free, you get it. If someone else got there first, you get the next free one withreason: "taken": your "claim lost, here's your new archipelago" answer. Re-sending a claim you already hold just confirms it.POST /claims/:cell/completemarks your cell complete. It then stays yours forever, with your name, and you can claim another.POST /claims/:cell/releasegives an unfinished cell back.GET /claims/melists your claims, oldest first.GET /claims/:cellreturns the claim, or{ archipelago, x, y, status: "uncharted" }.
One active claim per player: you can hold any number of completed cells, but only one unfinished one.
Idle claims go back to the sea. An active claim with no save or ping for 30 days becomes uncharted again. Completed claims never do. This runs as a daily job, and also a few at a time whenever a claim is handed out.
Offline first: let the game claim locally, then confirm with POST /claims/:cell when it's back online and follow archipelago in the answer.
Finds
First come, first served: a key can be found once, and the first player to report it keeps it, with their name. Use it for anything only one player can have, like a relic in a shared world.
POST /finds/:keyreports a find. The first player getsgranted: true; everyone after getsgranted: falseandfind.finder(id and name) andfind.foundAt. Asking again for a key you already found returnsgranted: true. Keys are 1 to 128 characters of letters, digits and: , . _ -, e.g.relic:t3:12,-4:a. Put a period (season, tide, week) in the key to let things be found again later.GET /finds?prefix=...lists finds whose key starts with the prefix, sorted by key (at most 100), e.g.prefix=relic:t3:12,-4:for everything found in one area this period. No player token needed.
Finds are decided by the same Durable Object as claims, so two simultaneous finds can't both win. Renaming a player updates their name on their finds.
Voyages: a ring world
A different way to lay out a shared world, where everyone starts the same distance from a centre and no spot is ever "taken". Every archipelago has an id (a cell like "412345,-80321", which you can use as its seed), a ring (how many crossings from the centre) and an angle round the centre. The id says nothing about where it is, so homes never fill a ring: every new player gets a home of their own on the starting ring.
Players move by sailing in (toward the centre), sideways (round the same ring) or out, and the server decides where they land:
| Sail | Lands on |
|---|---|
in |
One ring closer. With shareOdds (default 0.5) an archipelago another player is charting there right now (present in the last 30 days, lighthouse not yet lit), else a fresh one. Ring 0 is the centre (0,0 on layer 1). |
side |
The same ring, a little way round (turn: "cw" or "ccw"). On the starting ring, with homeOdds (default 0.3) another player's home; inside it, sharing like in; otherwise a fresh one. |
out |
One ring further, always a fresh archipelago. |
Rings inside the starting ring never hold homes.
Routes (the player token is needed except to read):
POST /voyages/home{ layer?, ring?, cell? }→{ home, here }. Makes the player's home on the starting ring (ring, default 5) the first time, then returns it.celllets an existing save keep its archipelago as its home if no one else uses that id. If the player isn't anywhere yet on this layer,hereis their home.POST /voyages/sail{ dir: "in" | "side" | "out", turn?, homeRing?, shareOdds?, homeOdds? }→{ from, dir, how, archipelago }.howis"fresh","shared","home"or"centre". Answers409 no_homebefore the first/voyages/home.POST /voyages/:cell/light→{ granted, archipelago }. Lights the lighthouse of the archipelago you're on; the first player to do it is remembered.409 not_hereanywhere else.POST /voyages/here{ cell, ring?, angle?, layer? }→{ here }. Puts the player on that archipelago, e.g. one they reached while offline; an id the server doesn't know becomes a fresh archipelago at that ring and angle.GET /voyages/me→{ homes, here }.GET /voyages/:cell→{ archipelago }.GET /voyages?layer=1→{ layer, centre, archipelagos }: every home, the centre, and every archipelago someone is on or has lit, each with who'spresent. No player token needed.
Every archipelago comes back as { archipelago, layer, ring, angle, kind: "home" | "wild" | "centre", home: { id, name } | null, lit: { by, at } | null, present: [{ id, name }], createdAt }. Layer n's centre is the cell ((n - 1) * 10000, 0). Saving or pinging keeps a player counted as present.
Neighbourhoods: homes on a shared grid
One shared grid where every player has a home square, for games where neighbours share the world (a sea of stations, a street of shops). Squares are cells like "3,-2"; your neighbours are the 8 squares around yours. The game decides how big a square is.
Placement keeps neighbourhoods even and friendly:
- A new player settles next to the player with the fewest neighbours.
- Nobody goes over the cap (
maxNeighbours, default 4): the new square must keep every home it touches at the cap or under. Since nobody fills all 8 squares, open squares are always left between homes. - Ties go nearest the middle (
0,0), with a little randomness, so the grid grows as a rough disc.
Quiet players. A home whose owner hasn't saved, pinged or opened their home for 30 days, and has no email attached, is freed for someone new (checked about once an hour). Nothing else of theirs is touched: the next time they settle they get a new square and returned: true. Players with an email keep their square however long they're away.
Moving next to a friend. One asks, the friend accepts, and the asker's home moves to a free square beside the friend's (straight squares first, then diagonals, then two out). At most once every 30 days. Homes placed this way don't count toward anyone's cap.
Visits. With visits set to "friends" (the default), players whose homes are 4 squares or fewer apart can also read each other's saves, so neighbours can see and visit each other's homes. "private" still means nobody.
Existing players. The first time a project uses homes, everyone already playing (seen in the last 30 days, or with an email) gets a square, oldest first.
Routes (the player token is needed except to read):
POST /homes/me{ maxNeighbours? }→{ home, neighbours, friends, asks, canMoveAt, settled, returned }. Settles the player the first time, then returns their home. Opening or settling counts as being seen.GET /homes/me→{ home, neighbours, friends, asks, canMoveAt }.homeisnulluntil they settle.friendslists your friends' homes wherever they are.GET /homes?square=0,0&radius=2→{ square, radius, homes }: every home withinradiussquares (at most 8) of a square. No player token needed.POST /homes/me/move{ to }→ asks friendtoto let you move beside them.403 not_friends,409 no_home,429 moved_recently.POST /homes/me/asks/:playerId{ accept: true | false }→ answers an ask. Accepting moves them beside you and returnsmoved(their new home).409 no_roomif every square near you is taken.DELETE /homes/me/asks/:playerIdwithdraws your ask, or turns down theirs.
asks is { incoming: [{ player, at }], outgoing: [{ player, at }] }. Every home comes back as { square, x, y, owner: { id, name }, via: "settled" | "friend", neighbours, settledAt, lastSeenAt }; neighbours counts only the ones toward the cap. Use lastSeenAt for "who's been around lately" (a lit window, a lantern).
Marks: buoys and signs on the shared grid
Small things a player leaves on the homes grid for everyone who passes, like the signs in Death Stranding: a buoy with a message, a cairn, a flag. Other players see who left it and can like it once. A mark sits in a square plus an offset inside it (dx, dy, in the game's own units). What it says is a sign number the game maps to its own list of messages: there's no free text, so there's nothing to moderate.
- Each player has at most 3 marks out. A new one replaces their oldest (its id comes back in
replaced). - Marks sink after 30 days.
- Drops are limited to 10 an hour per player, likes to 120 an hour. A muted player's marks are only shown to them.
Routes (the player token is needed except to read):
POST /marks{ square, dx, dy, sign, kind? }→{ mark, replaced }.signis a whole number from 0 to 999.kind(1-24 characters ofa-z0-9_-, default"mark") lets a game have more than one sort.GET /marks?square=0,0&radius=2&kind=buoy→{ square, radius, marks }: marks withinradiussquares (at most 8), newest first, at most 200. With a player token each mark also hasmineandliked.GET /marks/me→{ marks, limit }: your marks, each withlikedBy(the last 5 who liked it:{ id, name, at }).POST /marks/:id/like→{ mark }. Liking twice changes nothing.403 own_markon your own.DELETE /marks/:idtakes your own mark back in.403 not_yours.
Every mark comes back as { id, square, x, y, dx, dy, kind, sign, likes, owner: { id, name }, createdAt, sinksAt }.
World map
GET /map?x0=-10&y0=-10&x1=10&y1=10 → { x0, y0, x1, y1, archipelagos: [claim, …] } lists every claimed cell in the rectangle (corners inclusive), sorted by row. It can read at most 64 cells along each axis per request; page through larger areas.
Friend codes
Every player has a 6-character friend code (player.friendCode, no 0/O/1/I).
GET /friends/:coderesolves a code to a public profile.POST /players/me/friends{ code }links you and that player both ways. The code works like an invitation: it's what they chose to share. Limited to 20 attempts per hour and 200 friends.GET /players/me/friendslists your friends.DELETE /players/me/friends/:playerIdunlinks both ways.POST /players/me/friend-code→{ friendCode }replaces your code, so the old one stops working (existing friends stay).
Friends can visit a "friends" save, message a "friends" mailbox, and near puts new players beside them.
Mailboxes
Append-only messages to another player: gifts, messages in bottles, guestbook entries.
POST /mail/:playerId{ kind, body }(player token) →{ id, sentAt }.kindis a short lowercase word you choose (gift,bottle,guestbook…).bodyis any JSON up to 2 KB. You can send 30 messages an hour, and 5 an hour to the same player. Respects the recipient'smailsetting (403 mail_closed).POST /mail/bottle{ kind?, body }(player token) →{ id, sentAt }. Throws a message to a random stranger: someone seen in the last 14 days who takes mail from anyone and isn't a friend of yours. It drifts 20–60 minutes before it shows up in their mailbox, and you never learn who got it.kinddefaults tobottle. You can throw 6 an hour. If no one is out there, the answer looks the same and the bottle is lost at sea.GET /mail/me?limit=50&before=→{ messages: [{ id, kind, body, from: { id, name }, sentAt }], next }, newest first. Passnextasbeforefor older messages.DELETE /mail/me/:iddeletes one of your messages.POST /mail/me/:id/reportremoves it and queues a copy for you, the project owner.
Senders can't edit or delete what they sent. A mailbox keeps its newest 200 messages.
Moderation (secret key in apikey):
GET /mail/reportslists reported messages with the sender.PUT /players/:playerId/mutemutes a sender: their sends still get a normal answer, but nothing is delivered.DELETE /players/:playerId/mutelifts it.
Scoped leaderboards
A leaderboard can be scoped: one board per scope your game names, such as one per archipelago. Add "scoped": true to a board in the leaderboard config and pass scope when submitting:
lb.submit(run, { name, values: { beam: 42 }, scope: "3,-2" });
lb.top("beam:3,-2"); // board "beam", scope "3,-2"
Per-week boards are ordinary "period": "weekly" boards (fish with period key 2026-W41). A scoped board can have a period too, which gives one board per scope per week. See scoped boards.
Limits and billing
Everything here counts against your project's plan like other traffic: rows read and written, plus save blobs against the file-storage quota. Rough costs: a save writes 3 rows plus one R2 object, a claim about 3 rows, a message 3 rows. The data lives in reserved tables your own SQL can't see, it isn't part of SQL exports, and it is deleted with the project.
Busy days on the free tier. Free and anonymous projects share one daily allowance across all of Unbase. If it fills up, writes on those projects (sign-ins, saves, mail) answer 503 service_unavailable with a Retry-After until 00:00 UTC, while reads keep working. Projects on a paid plan are never paused. Games should keep playing offline and retry later.
Not here yet: real-time rooms (live positions over WebSockets) and per-project schedules beyond the built-in daily idle-claim job.