Skip to contentGo to cookie choices
Skip to docs navigation

Data (cloud save)

https://docs.zokogames.com/sdk/data

Purpose: SDK.data stores a small key/value save in the portal so progress follows the player across devices and survives cleared browser storage. The API deliberately mirrors localStorage:

TypeScript
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
clear(): void

Each call coerces its arguments with String(), so setItem("level", 3) stores "3". getItem returns null for a key that was never set. Setting a key to the value it already has does nothing (no upload). removeItem of a missing key and clear() on an empty save do nothing either.

All four are synchronous. The whole save is loaded when init() resolves, so reads never wait. Writes update memory immediately and sync to the portal in the background.

JavaScript
await SDK.init();

const level = Number(SDK.data.getItem("level") ?? "1");

function onLevelComplete(next) {
  SDK.data.setItem("level", String(next));
  SDK.data.setItem("stars", JSON.stringify(stars));
}

Values are strings. Store structured state with JSON.stringify and parse defensively.

At a glance#

Every member of SDK.data, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.

Signature Returns Can fail with Since
getItem(key: string): string | null The saved string, or null for a key that was never set. Synchronous. Throws dataModuleDisabled, sdkNotInitialized, sdkDisabled. 1.0.0
setItem(key: string, value: string): void Nothing. Memory changes at once; the upload follows in the background. Throws dataLimitExceeded (nothing is written), dataModuleDisabled, sdkNotInitialized, sdkDisabled. 1.0.0
removeItem(key: string): void Nothing. Throws dataModuleDisabled, sdkNotInitialized, sdkDisabled. 1.0.0
clear(): void Nothing. Throws dataModuleDisabled, sdkNotInitialized, sdkDisabled. 1.0.0
mirrorLocalStorage(options?: MirrorLocalStorageOptions): () => void A function that stops mirroring. Does nothing when the SDK is disabled. Throws dataModuleDisabled, sdkNotInitialized. 1.4.0
mirrorIndexedDB(options?: MirrorIndexedDBOptions): Promise<() => void> A promise that resolves, after any restore, with a function that stops mirroring. Resolves with a no-op function when the SDK is disabled or the browser has no IndexedDB. Rejects with dataModuleDisabled, sdkNotInitialized, invalidArgument (no databases given and the browser cannot list them). 1.7.0

MirrorLocalStorageOptions is { keys?: string[] | RegExp; prefix?: string; onError?: (error: SdkError) => void }. The type DataApi is in the declaration file described in the SDK introduction. Mirroring keeps its own bookkeeping in the reserved cloud key __zoko_ls_mirror_ts, which counts toward the 1 MiB save limit; do not use that key yourself.

Lifecycle#

init() resolves                 whole save already in memory
  -> getItem(...)               read, no waiting
  -> setItem / removeItem / clear   memory changes at once, upload scheduled
       1 s of quiet  OR  30 s since the first unsent change  OR  page hidden / closed  -> upload
       upload fails -> data stays in memory, retried after 2 s, 4 s, ... up to 60 s, or sooner with the next write

How syncing works#

  • Writes are debounced by one second: several setItem calls in a burst become one upload.
  • If writes keep arriving, an upload still goes out at least every 30 seconds.
  • Pending writes are sent immediately when the page is hidden or closed (visibilitychange to hidden, pagehide).
  • If an upload fails, the data is kept in memory and retried on its own after 2, 4, 8 seconds and so on up to 60 seconds, and sooner with the next write or when the page is hidden. The failure is not surfaced to your game: setItem has already returned, no promise rejects and no event fires (there is no flush call to wait on either). The SDK only logs data sync failed to the console. A game cannot tell that a background upload is failing, so treat the cloud save as best effort and keep playing from memory.
  • While the player is offline the portal keeps the changes on the device and uploads them when the connection returns (for a signed-in player).

Guests and signed-in players both get a save, but it lives in different places:

  • Signed-in players: the save is stored on the portal's servers and follows the account across devices and browsers.
  • Guests: the save is kept in the browser's localStorage of the portal page, which the portal writes for your game when the SDK syncs. It is not your game's own localStorage: the game frame runs on its own origin and has its own, separate storage, which the SDK never reads or writes. A guest's save survives reloads and later visits in the same browser, but not a cleared browser, a private window or another device; the portal may offer to sign in so the save is not lost.
  • When a guest signs in while playing, their save is uploaded if the account has no save for your game yet. If the account already has a different save, the portal asks the player which copy to keep: until they answer, your game keeps the guest's data and its writes stay on the device, and choosing the account's copy reloads your game (see Guests and signing in). Plan for both outcomes: never assume the data you loaded at start is still the data in the store.
  • After a sign-out or a switch to another account, the portal restarts your game. Until it does, setItem, removeItem and clear behave as usual but the change is not stored. A signed-in player's changes that had not been uploaded when they signed out are uploaded, not replaced by the older cloud save, when the same player signs in again.
  • Kids mode: saves stay on the device and are never uploaded. SDK.data works as for a guest: getItem returns what your game saved on this device in kids mode, never anything from a signed-in parent's account. A kids-mode save belongs to no account, so it is never merged into an account's cloud save, and it is not adopted or uploaded when kids mode ends and an adult is signed in. Changes that could not be uploaded (offline, a failed upload, a closed tab) are remembered on the device for that player alone and are offered again the next time the same player is signed in; see kids mode.
  • Two copies of the SDK in one game frame (for example an engine plugin and a script tag, or your game reloading its own document) share one load: the second init() gets the same save as the first. If the player signed in since the frame started, the second copy waits briefly for the portal to finish the sign-in comparison; if the frame was started for a different player, its init() is refused and that copy stays "disabled" until the game is reloaded.
  • While the player deletes the cloud save (Delete cloud save in the game page menu), uploads stop, and an init() that arrives meanwhile is refused: that SDK copy stays "disabled". When the delete succeeds the game restarts from an empty save, in this tab and in the player's other tabs; if it fails, the player is offered a reload.
  • A deleted cloud save is not brought back: when the player deleted the cloud save from another tab or device, an upload written against that save is refused (HTTP 409 save_gone) and the SDK reports a generic save failure, so keep playing with the local copy and do not retry the upload in a loop.
  • After a player deletes a game's cloud save, the portal remembers the deletion for 90 days. A device that still holds the old progress does not upload it silently: the player is asked whether to keep that device's progress or delete it there too, and until they answer nothing is uploaded and the game keeps running on its local copy. After 90 days an old device saves as normal. The game needs no code for this: the SDK.data calls behave as usual, and a write the portal holds back is not an error (nothing throws and no event fires).

Limit#

The whole save, serialised as JSON, must not grow past 1,048,576 bytes (1 MiB). The size is measured on the whole save as one JSON object of key/value strings, in UTF-8 bytes. The limit is on the whole save, not on a key: there is no separate per-key limit, so one value may use almost all of it, and every key's name, quotes and separators count too. Ten keys of 100 KiB each are over the limit, and so is one key of 1 MiB. A setItem that would exceed it throws dataLimitExceeded and changes nothing; that is the only limit error your code sees, and it is raised at write time, never by a later background upload.

The portal also checks a few things the SDK does not: a key name of more than 256 characters, or a key or value that contains the character U+0000, makes the portal refuse the whole upload, and the top-level key names constructor and prototype are dropped. One account holds at most 25 MiB of cloud saves across all games; when it is full, progress stays on the device. None of these is reported to your game, so keep key names short and plain.

JavaScript
try {
  SDK.data.setItem("replay", bigString);
} catch (e) {
  if (e.code === "dataLimitExceeded") SDK.data.removeItem("replay");
}

Keep saves compact: store ids and numbers, not whole world snapshots.

Errors#

Code Thrown by Meaning
dataLimitExceeded setItem The write would push the save over 1 MiB. Nothing was written.
dataModuleDisabled all four methods The data module is not enabled for this game. In the console open the game's Technical step, turn on Uses the SDK data module and save. The game reads the setting when it starts.
sdkNotInitialized, sdkDisabled all four methods See errors.

removeItem and clear never throw dataLimitExceeded. The code other is part of the data code list but the SDK does not raise it for these calls.

Because these methods are synchronous they throw rather than reject. dataModuleDisabled is thrown by every method, including getItem.

Ordering. Every method needs init() to have resolved: before that, and in the "disabled" environment, it throws sdkNotInitialized or sdkDisabled, so read the save only after await SDK.init(). When the game is not allowed to use cloud saves (dataModuleDisabled) fall back to your own in-memory state. Writes made in the first moments after a sign-in or a sign-out are covered above.

Common mistakes. The ones the Preview checklist and QA report most often:

Mistake Result Fix
A save is written on every frame or every click Many uploads that are only coalesced, not avoided Write when the state changes meaningfully (a level, a purchase) and let the SDK debounce.
One big JSON snapshot of the whole world is stored dataLimitExceeded at 1 MiB, and a Preview check fails when the save reaches 1,048,576 bytes Store ids and numbers; keep replays and assets on your own storage.
setItem is not wrapped in try/catch An uncaught dataLimitExceeded stops the game loop Catch it and drop the least useful key.
SDK.data.setItem("level", 3) is read back as a number getItem returns "3" Parse: Number(SDK.data.getItem("level") ?? "1").
The game keeps using localStorage and SDK.data for the same keys Two saves that drift apart Pick one, or use mirrorLocalStorage for a ported game.
mirrorLocalStorage is called after the game has read its saves The game starts from the old local values Call it right after init() and before the first read.
mirrorIndexedDB() is not awaited before the engine starts The engine reads the old local files await it, then start the engine.
localStorage.level = 3 is used while mirroring The write is not seen Use localStorage.setItem.
A failed upload is expected to reject or fire an event Nothing is reported; only a console message Treat the cloud save as best effort and keep playing from memory.
Local mode is used to test dataModuleDisabled It cannot happen locally (always enabled) Catch dataModuleDisabled anyway, and test the real setting in the Preview tool.

When to use something else#

  • Progress that must be shared between your own services, or tied to purchases, belongs on your server with the verified token.
  • Large assets and replays belong on your own storage.
  • Anything you cannot afford to lose should also be stored in a way you can recover. Treat cloud save as convenient, not as a database.

In local mode, as a guest, offline or ad-free#

Situation Behaviour
Local mode The save lives in localStorage under the key zoko-sdk-data and is always enabled, so dataModuleDisabled cannot be tested locally. Delete that key (or use an incognito window) to simulate a new player. The 1 MiB limit and the debounce are the same.
Basic launch No difference: the save works as in full launch, as long as Uses the SDK data module is on.
Signed-in player Save stored on the portal and merged as described above.
Guest Save kept in the browser for the portal; the portal may offer to sign in so the save is not lost.
Offline Reads and writes work from memory and the device copy; upload resumes online.
Ad blocker / ad-free No effect.

Mirroring localStorage (ported games)#

Added in SDK 1.4.0. A game that already saves with localStorage can get cloud saves without code changes. Call this once right after init(), before the game reads its saves:

JavaScript
await SDK.init();
const stop = SDK.data.mirrorLocalStorage({ prefix: "mygame_" }); // or { keys: ["save", "settings"] } or { keys: /^slot\d$/ }

Nothing is mirrored unless you call it. With no keys and no prefix every key is mirrored (a key matches when it is in keys, matches the expression, or starts with prefix). The function it returns stops mirroring.

  • Writes: localStorage.setItem, removeItem and clear on the page's own localStorage are copied into the cloud save under the same key, 2 seconds after the last write (at most every 10 seconds under steady writes, and at once when the page is hidden or closed). sessionStorage is never touched. Assigning localStorage.key = value or localStorage["key"] = value bypasses the methods and is not seen; use setItem.
  • Restore on call: the SDK keeps one timestamp per key (a reserved key, __zoko_ls_mirror_ts, in both places; do not use that name). For each key the newer side wins, and a deletion counts as a write. A key only one side has is copied to the other. On equal timestamps nothing changes.
  • Quota: the cloud save is still limited to 1 MiB. A key that does not fit stays in localStorage only and is reported through onError(error) with code dataLimitExceeded (default: console.error); other keys keep syncing.
  • Does nothing when the SDK is disabled; throws dataModuleDisabled when cloud saves are off for the game and sdkNotInitialized before init() resolves. Mirrored keys share the cloud save with setItem, so a key written by both is overwritten by whichever wrote last.

Mirroring IndexedDB (Unity, Godot, GameMaker)#

Added in SDK 1.7.0. Engines that save into IndexedDB (Unity's /idbfs, Godot's user file system, GameMaker) get cloud saves without code changes. Opt-in, like mirrorLocalStorage. Await it before the engine starts: the restore happens inside the promise, and an engine that reads its files before the promise resolves sees the old local data and may overwrite the cloud copy with it.

JavaScript
await SDK.init();
const stop = await SDK.data.mirrorIndexedDB({ databases: ["/idbfs/mygame"] });
startEngine(); // only now

Options (MirrorIndexedDBOptions): databases (names to mirror; default: every database indexedDB.databases() lists except engine asset caches such as UnityCache, and required when the browser cannot list databases), maxBytes (a lower cap; never above the 1 MiB save limit), debounceMs (default 2000), pollMs (default 5000) and onError(error) (default console.error). Pass databases whenever you know the names: it is faster and keeps big asset caches out.

  • Storage: the snapshot is one reserved cloud key, __zoko_idb_mirror, a versioned JSON string with each database's version, object stores (key path, auto-increment, indexes) and records. Binary values (ArrayBuffer, typed arrays, Blob) are base64, dates and Map/Set/bigint are tagged. Binary grows by about a third, and the whole snapshot counts toward the same 1 MiB save limit as everything else in SDK.data; do not use that key yourself.
  • Limit: a snapshot that would not fit is never truncated. That cycle is skipped, IndexedDB and the last cloud copy stay as they are, and onError gets dataLimitExceeded once (until a cycle fits again). A value the encoding cannot carry (a function, a cyclic object) is reported the same way.
  • Restore: when the cloud copy is newer than this device's last sync, it is written back into IndexedDB: stores in the snapshot are replaced, and databases and stores that are not in the snapshot are never deleted or touched. A missing database is created at the snapshot's version; an existing one is only upgraded to a higher snapshot version, and a store whose key path differs is skipped and reported. An empty local database never replaces cloud data. On equal timestamps nothing changes. Restore stops waiting after 10 seconds so the game still starts.
  • Changes: IndexedDB has no change event, so the SDK polls while the page is visible (counts every 5 s, a full read about every 15 s) and checks again when the page is hidden or closed. A change is uploaded after it has been stable for 2 seconds (at most every 10 seconds under steady writes). A save made in the last moments before the tab closes can be lost, because IndexedDB reads are asynchronous.
  • Not mirrored: Cache Storage, OPFS and cookies.

Migrating from localStorage#

JavaScript
const migrated = SDK.data.getItem("migrated") === "1";
if (!migrated) {
  for (const key of ["level", "stars", "coins"]) {
    const v = localStorage.getItem(key);
    if (v !== null) SDK.data.setItem(key, v);
  }
  SDK.data.setItem("migrated", "1");
}

Next steps#

Something unclear, wrong or missing on this page? Tell us through support · Test your game in the preview tool