# Player data Per-player, per-game storage with the injected window.GBG client: key bindings, settings, cloud saves across devices, and async multiplayer (raids, clans). No API key or game ID goes in your game. Every player who opens your game on Good Browser Games has an identity, signed in or not. Signed-out players are guests. When a guest signs in, their data moves to the account. If both had the same key, the account copy stays and the guest copy moves to _claimed/KEY for 30 days, and GBG emits an identity event so your game can ask which save to keep. The same calls work with no player (your game on another site, or opened directly): GBG.data then stores in localStorage with the same API. Multiplayer calls reject with error code no_player there. ## Scopes and limits Each key has a scope. private: only the player and your server read it (key bindings, settings, saves). public: any player of your game can read it (a base layout, avatar, deck). protected: anyone reads it but only your server writes it, with your publisher key (trophies, gold, ranked rating). Every key has a rev, a whole number that rises with each write. A write with ifRev applies only if the key is still at that rev (0 means the key must not exist); otherwise it returns 409 conflict with the current rev and value. A write without ifRev is last-write-wins. GBG.data.set sends the last rev the tab saw, so a stale tab gets a conflict event instead of overwriting newer progress; GBG.data.update re-reads and retries for you. Limits per player per game: 64 KB per value (as JSON), 1 MB in all, 100 keys (_claimed/ copies do not count), 60 writes a minute, and an IP cap. Over a limit, writes fail with 413 too_large or 413 quota, which the SDK does not retry; 429 rate_limited and 5xx answers are retried up to 3 times with backoff. Keys are 1 to 128 characters of letters, numbers, and _ . : / -. Every response carries the server clock in the X-GBG-Time header; GBG.serverTime() uses it, so offline progress cannot be cheated with the device clock. Writes take an opId; a retried write with the same opId within 24 hours applies once and returns the first answer. Players see and delete each game's data in their profile. Deleting an account deletes its data. Guests idle for 180 days are deleted. You moderate the public text in your game; you can rewrite or delete any player's key with your publisher key. ## JavaScript await GBG.ready(); // {ref, guest, claimed, local} const binds = await GBG.data.get('keybinds'); // null when unset const { save, settings } = await GBG.data.getMany(['save', 'settings']); // one request GBG.data.set('keybinds', { jump: 'Space' }); // debounced; flushed with keepalive on pagehide GBG.data.set('base', layout, { scope: 'public' }); await GBG.data.update('progress', p => ({ ...p, level: (p?.level ?? 0) + 1 })); // rev-checked retry await GBG.data.inc('stats', 1, { path: 'wins' }); // atomic; optional min, max await GBG.data.append('log', entry, { cap: 200 }); // atomic; drops the oldest past cap await GBG.data.setIfAbsent('created', GBG.serverTime()); await GBG.data.delete('old'); const { keys, usage } = await GBG.data.list(); await GBG.data.flush(); // send debounced writes now GBG.on('conflict', ({ key, local, remote, rev }) => {}); // a stale set was refused GBG.on('identity', ({ claimed }) => {}); // e.g. claimed: ['save'] after a guest signs in const theirs = await GBG.data.get('_claimed/save'); GBG.on('error', ({ key, error }) => {}); // a background write failed const now = GBG.serverTime(); // Off Good Browser Games, or with your own Content-Security-Policy, load the // client yourself and name your game first: // // GBG.gameId = 'GAME_ID'; ## Async multiplayer (JavaScript) GBG.me.ref; // this player's public name, gbgr_... await GBG.match.join('raid', { rating: 1240 }); const foe = await GBG.match.find('raid', { spread: 200, key: 'base' }); // {ref, handle, rating, lease, rev} or null const base = await GBG.players.get(foe.ref, 'base', { lease: foe.lease }); // the snapshot pinned at rev await GBG.match.release(foe.lease, { shieldMs: 8 * 3600e3 }); // keeps the target out of find (24 h max; your server can set up to 7 days) await GBG.inbox.send(foe.ref, 'raid', { stars: 2 }); const { messages, nextCursor } = await GBG.inbox.list({ limit: 50 }); await GBG.inbox.ack(messages.map(m => m.id)); // A find leases one target to one attacker for 3 minutes (leaseMs up to 10). // Finding drops your own shield and any lease you still held. ## Groups (JavaScript) const group = await GBG.groups.create({ name: 'Reef Riders', maxMembers: 30 }); await GBG.groups.join(groupId); await GBG.groups.leave(groupId); const open = await GBG.groups.list({ q: 'reef' }); // open groups const mine = await GBG.groups.mine(); // with your role await GBG.groups.setRole(groupId, ref, 'elder'); // founder only await GBG.groups.kick(groupId, ref); // elders kick members; the founder kicks anyone const reef = GBG.groups.data(groupId); // shared documents, members only await reef.set('project/kelp', { shells: 0, goal: 500 }, { writeRole: 'member' }); // elders create keys await reef.inc('project/kelp', 3, { path: 'shells' }); await GBG.groups.send(groupId, 'news', { done: 'kelp' }, { fanout: true }); // elders: also every member inbox const news = await GBG.groups.inbox(groupId); ## Unity WebGL (C#) // Assets/Plugins/WebGL/GBGData.jslib. Strings cross as JSON; results come back by SendMessage. mergeInto(LibraryManager.library, { GBGDataSet: function (key, json) { if (window.GBG) window.GBG.data.set(UTF8ToString(key), JSON.parse(UTF8ToString(json))).catch(console.warn); }, GBGDataGet: function (key, objectName, method) { var k = UTF8ToString(key), o = UTF8ToString(objectName), m = UTF8ToString(method); var get = window.GBG ? window.GBG.data.get(k) : Promise.resolve(null); get.then(function (v) { SendMessage(o, m, JSON.stringify(v)); }, function () { SendMessage(o, m, 'null'); }); } }); // C#. Add using System.Runtime.InteropServices. #if UNITY_WEBGL && !UNITY_EDITOR [DllImport("__Internal")] static extern void GBGDataSet(string key, string json); [DllImport("__Internal")] static extern void GBGDataGet(string key, string objectName, string method); #else static void GBGDataSet(string key, string json) {} static void GBGDataGet(string key, string objectName, string method) {} #endif void Save(SaveData save) => GBGDataSet("save", JsonUtility.ToJson(save)); void Load() => GBGDataGet("save", gameObject.name, nameof(OnLoaded)); void OnLoaded(string json) { if (json != "null") save = JsonUtility.FromJson(json); } ## Godot 4 (GDScript) # Save: stores any Dictionary as JSON. Does nothing outside a web export. func save_data(key: String, value) -> void: if OS.has_feature("web"): JavaScriptBridge.eval("window.GBG && GBG.data.set(%s, %s)" % [JSON.stringify(key), JSON.stringify(value)]) # Load: GBG puts the value on window for the next frame to read. func load_data(key: String) -> void: if OS.has_feature("web"): JavaScriptBridge.eval("window.GBG && GBG.data.get(%s).then(v => window.gbgLoaded = JSON.stringify(v))" % JSON.stringify(key)) func _process(_delta): if OS.has_feature("web"): var loaded = JavaScriptBridge.eval("window.gbgLoaded || ''") if loaded != "": JavaScriptBridge.eval("window.gbgLoaded = ''") var save = JSON.parse_string(loaded) ## Publisher API Your server uses Authorization: Bearer YOUR_PUBLISHER_KEY without Cookie or Origin headers: games:read for reads, games:write for writes. Name a player by ref (gbgr_...) or by the gbgp_ ID a client sends your server; GET /players/ID returns the ref. Paths below are under /api/v1/games/GAME_ID. GET /players/REF and GET /players/REF/data GET, PUT, PATCH, DELETE /players/REF/data/KEY. PUT body {value, scope?, ifRev?, opId?}. PATCH body {op: inc|append|setIfAbsent|set, by?, value?, path?, cap?, min?, max?, ifRev?, opId?}. DELETE takes ?ifRev=. POST /data/batch with {opId?, ops: [{ref | group, key, op, ...}], messages: [{to | group, kind, body, from?, fanout?}], releases: [{lease, shieldMs?, requireActive?}], checks: [{group, ref, minRole?}]}: up to 50 items in one transaction, applied all together or not at all. A stale ifRev, a min or max, a limit, a release with requireActive:true of an expired or released lease (409 lease_ended), or a check whose player is no longer in the group at minRole (403 forbidden) fails the whole batch. Give a group document scope protected from your server to make it server-only; members still read it. POST /players/REF/inbox with {kind, body, from?}; GET /players/REF/inbox?cursor= GET /match/POOL?cursor=; PUT /match/POOL/players/REF {rating, shieldUntil?}; DELETE /match/POOL/players/REF GET /match/POOL/leases/LEASE returns the target, attacker, key, pinned rev, and snapshot; POST /match/POOL/leases/LEASE/release {shieldMs?} GET, POST /groups (POST {name, founder: REF, open?, maxMembers?}); GET, PATCH /groups/GROUP ({name, open, maxMembers, status: active|archived}) POST /groups/GROUP/members {ref, role?}; PATCH, DELETE /groups/GROUP/members/REF GET, PUT, PATCH, DELETE /groups/GROUP/data/KEY; GET /groups/GROUP/data POST /groups/GROUP/inbox {kind, body, fanout?}; GET /groups/GROUP/inbox GET, PUT, DELETE /webhook. PUT {url, events?} returns the signing secret once. POST /test-players {count: 1-100} mints guest players for your bot scripts (1000 per game); they skip the IP cap. A Worker in the same Cloudflare account as a Good Browser Games Worker cannot fetch it on its workers.dev URL; use a service binding to that Worker instead. Webhook deliveries POST {id, event, gameId, at, data} with X-GBG-Signature: t=MS,v1=HEX, the HMAC-SHA256 of "MS.BODY" keyed with the secret. Events: group.created, group.member.joined, group.member.left, group.member.removed, group.role.changed, group.archived, group.message. Delivery is best effort with a 5 second timeout. ## Player API The SDK calls these with the gbgp_ ID in an X-GBG-Player header. CORS allows only your game's origin and the play host. Paths are under /api/v1/games/GAME_ID: GET /me; GET /me/data; GET, PUT, PATCH, DELETE /me/data/KEY (an unset key answers 200 with value null and rev 0; GET /me/data?values=1 includes values); GET /players/REF, /players/REF/data, /players/REF/data/KEY?lease=; POST /me/match/POOL/join, /find, /release, /leave; POST and GET /me/inbox, POST /me/inbox/ack; GET /groups, /groups/GROUP; GET and POST /me/groups; POST /me/groups/GROUP/join, /leave, /kick, /role; GET /me/groups/GROUP/data; GET, PUT, PATCH, DELETE /me/groups/GROUP/data/KEY; POST and GET /me/groups/GROUP/inbox. Errors use {error, message}.