Skip to content

Persistent State

An HTML artifact can have persistent state: data the page saves and gets back the next time anyone opens it. A checklist that stays ticked, a poll everyone votes in, an RSVP list for an event, a scoreboard, someone’s progress through a guide. The state stays with the artifact, and the artifact’s rules decide who can see and change each part of it.

You don’t need to write any code. Ask the agent for what you want, for example:

  • “Make the checklist remember what’s ticked, for everyone on the project.”
  • “Add a poll where each person votes once and everyone sees the results.”
  • “Turn this invite into an RSVP form. Guests shouldn’t need an account, and only we should see the answers.”

The agent builds the page and sets the rules it needs.

Open an HTML artifact and choose Persistent state in its More actions (⋯) menu.

  • Data lists what the page has saved, as you are allowed to see it. Mine shows only what it keeps for you. You can export everything as JSON, and delete entries the rules let you delete.
  • Rules, for Editors and the creator, shows who can see, add, change and delete each part. There they can change the rules and confirm rule changes an agent asked for. They can also delete all of its data.

Saving happens as people use the page. Changes show up for everyone who has it open without a reload: within a second or two for anyone signed in, and within a minute for visitors on a share link who aren’t.

What a page saves is organized by keys: paths like tasks/venue, votes/7f3ac1d29e0b44a1 or rsvps/0193f4a2. Rules say, for each path, who can see, add, change and delete what is saved there. ShareCube checks them on every read and every change, wherever it comes from: the page, the Persistent state panel, or an agent. A page can’t get around them, and neither can someone calling the API directly.

What you can do depends on your level on the artifact, which comes from how you reached it:

You areYour level
Owner or Editor of the project (or of the artifact, shared from another organization)Editor
The person who created the artifact, while they’re still an Editor or OwnerCreator, above Editor
A Commenter, or in your organization and in through a link set to CommenterCommenter
A Viewer, or in your organization and in through a link set to ViewerViewer
Not signed in, or signed in to another organization and in only through the public linkAnyone

Persistent state never gives you more than you have on the artifact itself: if you can’t open the artifact, you can’t reach its data.

Every artifact has these two rules, and its own rules sit on top of them:

PathSeeAdd, change, delete
EverythingViewers and upCommenters and up
users/<each person>Only that personOnly that person

So without rules of its own, a page’s data is shared by everyone who can open the artifact and changed by Commenters and up, and every person, Viewers included, has a private space under users/ that no one else can read, not even the creator.

A rule is a path and the lowest level allowed to do each thing there. Editors can see and edit a page’s rules as JSON under Persistent state → Rules → Edit rules as JSON:

[
{ "path": "votes", "read": "viewer", "write": "editor" },
{ "path": "votes/{self}", "write": "self" }
]
FieldMeaning
pathThe part of the data the rule covers, like votes or tasks/done. "" means everything.
readWho can see entries there.
createWho can add new entries.
updateWho can change existing entries.
deleteWho can delete entries.
writeShorthand for create, update and delete together. Any of the three set on its own wins over it.
maxAt most this many entries under the path, from 1 to 25,000. A max above what the plan allows never comes into play.

The levels you can use:

LevelWho
anyoneAnyone with the link, signed in or not. Counts only while the artifact is public.
viewerViewers and up.
commenterCommenters and up.
editorEditors and up (Owners included).
creatorOnly the artifact’s creator.
selfOnly the person the entry belongs to. Only on a path ending in {self}.
noneNo one.

For each action on a key, ShareCube looks for the deepest rule whose path covers the key and that says something about that action. A rule that leaves an action out passes it up to the rule above it, and in the end to the defaults.

Say a page has one rule, { "path": "tasks", "write": "editor" }. For the key tasks/venue:

  • see: the tasks rule doesn’t say, so the default for everything applies: Viewers and up.
  • add, change, delete: the tasks rule says Editors and up.

A rule with the same path as a default replaces that default. { "path": "", "read": "editor", "write": "editor" } makes everything Editor-only, while users/<each person> stays private.

{self}, as the last part of a path, stands for each person’s own id on this artifact. votes/{self} covers votes/<my id> for me and votes/<your id> for you, and the self level means only that person. A page gets the id from await sharecube.state.me(): a promise that resolves to a string like 7f3ac1d29e0b44a1, different on every artifact, that doesn’t reveal who the person is. It’s never their name.

Other people’s entries under a {self} path are hidden, even from the creator, unless a rule on the path above opens them. That rule has to say both who sees and who changes them. In the votes example, the votes rule lets everyone see every vote and Editors change any vote, while votes/{self} lets each person add and change only their own.

People without an account have no id, so {self} paths don’t apply to them.

A set of rules is checked when it’s saved and refused as a whole if something is wrong, with the reason:

  • Changing what you can’t see. After passing actions up to the rules above, nobody may be allowed to change or delete entries they can’t see. { "path": "rsvps", "read": "editor", "create": "anyone" } is refused: update and delete would fall to the default (Commenters) while only Editors can see. Say "update": "none", "delete": "editor" as well. Adding is the exception: people can be allowed to add where they can’t see, which is how a write-only list works.
  • self on a path that doesn’t end in {self}, {self} anywhere but the end of a path, or {self} on its own.
  • max on everything or on a {self} path, or one that isn’t a whole number from 1 to 25,000.
  • The same path twice, an unknown field, a rule that sets nothing, or more than 64 rules.

When something isn’t allowed, a page is told the entry doesn’t exist, whether it’s missing or hidden. So a page can’t find out what it isn’t allowed to see by trying.

Only Editors and the creator. Rules name the parts of the data other people can’t reach and say who can, so nobody else is shown them, in the app, through the API or through an agent. Everyone else simply finds what they’re allowed to see.

Editors and the creator change them in the Persistent state panel or through an agent. Rules an Editor saves in the app apply at once. Rules an agent sets apply at once too, unless they let in people without an account: those wait for an Editor to confirm them (see below). If someone else changed the rules while you were editing, your save is refused instead of quietly undoing theirs; reload and try again.

Delete all data is for Editors and the creator, whatever the rules say.

A shared checklist (no rules needed). The defaults already let everyone with access see it and Commenters tick it.

One vote each, results for everyone:

[
{ "path": "votes", "read": "viewer", "write": "editor" },
{ "path": "votes/{self}", "write": "self" }
]

The page saves each vote at votes/<me>. Everyone sees the tally, each person changes only their own vote, and Editors can remove any.

An RSVP list guests can’t read, on a public artifact:

[
{ "path": "rsvps", "read": "editor", "create": "anyone", "update": "none", "delete": "editor", "max": 200 }
]

The page adds entries with add("rsvps", { name, guests }). Anyone with the link can RSVP, without an account. Only Editors see the list, nobody can edit an entry once it’s in, Editors can delete one, and it stops at 200.

A public leaderboard only Editors update:

[
{ "path": "scores", "read": "anyone", "write": "editor" }
]

Settings only the creator controls:

[
{ "path": "config", "read": "viewer", "write": "creator" }
]

This part is for the agent building the page. Decide the keys first, then the rules that fit them.

  1. Lay out the keys. One entry per thing, grouped by who may change it: cards/<id> for a shared board, votes/<me> for one vote each, users/<me>/... for things only that person sees.
  2. Check whether the defaults already fit. Everyone with access sees everything, Commenters and up change it, and users/<me>/ is private. A shared checklist or a team board needs no rules at all.
  3. Read the current rules with get_artifact_state_rules.
  4. Set them with set_artifact_state_rules. It replaces the whole list, so always send every rule the page needs, not just the new one. [] goes back to the defaults. Only Editors and the creator can set rules.
  5. Tell the person when rules are pending. Rules that let in anyone (people without an account) don’t apply until an Editor confirms them under Persistent state → Rules. Until then, visitors’ saves are refused. The tool’s answer says so; pass it on.
  6. Build keys with the person’s id, never the text {self}. {self} only appears in rules. The page writes 'votes/' + await state.me(), and braces aren’t allowed in keys anyway.

Common pages and the rules they need (each of these is accepted as written):

The pageKeysRules
Shared checklist or team kanban boardtasks/<id>, cards/<id>None
Same, but Viewers can move cards toocards/<id>[{ "path": "cards", "write": "viewer" }]
Same, but only Editors change the boardcards/<id>[{ "path": "cards", "write": "editor" }]
Poll: one vote each, everyone sees the tallyvotes/<me>[{ "path": "votes", "read": "viewer", "write": "editor" }, { "path": "votes/{self}", "write": "self" }]
Game leaderboard: each player sets only their own scorescores/<me>[{ "path": "scores", "read": "viewer", "write": "none" }, { "path": "scores/{self}", "write": "self" }]
Survey: each person sees only their own answers, Editors see allanswers/<me>[{ "path": "answers", "read": "editor", "write": "editor" }, { "path": "answers/{self}", "read": "self", "write": "self" }]
Personal progress or settingsusers/<me>/...None
Public RSVP that guests can’t readrsvps/<id> from add[{ "path": "rsvps", "read": "editor", "create": "anyone", "update": "none", "delete": "editor", "max": 200 }] (pending until confirmed)
Public guestbook everyone can readguestbook/<id> from add[{ "path": "guestbook", "read": "anyone", "create": "anyone", "update": "none", "delete": "editor", "max": 500 }] (pending until confirmed)
Settings only the creator changesconfig/...[{ "path": "config", "read": "viewer", "write": "creator" }]

Mistakes ShareCube refuses, with the reason in its answer:

  • Write-only without the rest. { "path": "rsvps", "read": "editor", "create": "anyone" } is refused because update and delete would fall back to Commenters, who can’t read the entries. Say "update" and "delete" too.
  • A {self} rule whose parent doesn’t say enough. The rule above a {self} path has to set both read and write, since it decides who sees and changes everyone else’s entries. [{ "path": "answers", "read": "editor", "update": "none", "delete": "editor" }, { "path": "answers/{self}", "write": "self" }] is refused with Rule "answers" sits above "answers/{self}", so it must set read and write.

And things that work but surprise people:

  • People without an account have no id, so they can’t save under a {self} path. A game that visitors play can keep their score in memory or in localStorage, or ask them to sign in.
  • can() answers from the rules that apply to this person, but the server has the last word, so still handle a refused call.
  • Rules don’t change data that’s already saved. Tightening them hides or locks existing entries; it doesn’t delete them.

On a public artifact, rules can let anyone with the link add data. They don’t need a ShareCube account.

  • When an agent sets rules like that, they don’t apply right away. They wait under Persistent state → Rules until an Editor confirms them. Rules an Editor saves in the app apply immediately.
  • What a visitor can save is smaller than for people with an account, and how often is limited.
  • People signed in to another organization who open the artifact through its public link count as visitors too.

Agents connected over MCP can read and change an artifact’s state as you, within the same rules: “who has signed up so far?”, “add Sam to the guest list”, “clear last week’s votes”. State keeps no history, so a change or a delete can’t be undone.

This part is for developers and for the agents that build pages. HTML pages get an API at window.sharecube.state. It’s ready before the page’s own scripts run, so there’s nothing to import.

These are the mistakes agents make most often. Each one gives you a page that looks right and then doesn’t save or doesn’t update.

  • me() is async, and it’s an id, not a name. await sharecube.state.me() resolves to an opaque id like 7f3ac1d29e0b44a1, the same for that person every time on this artifact and different on every other artifact. It is never a name or an email, and it’s null for people without an account. To show who did something, have the page ask for a name and save it along with the entry.
  • Wait for ready once, before anything else. await sharecube.state.ready, then read sharecube.state.available. Before ready resolves, available is false and can() answers false for everything.
  • can() is the one call that isn’t async. It returns true or false straight away, so call it after ready and don’t await it.
  • One entry per thing, not one big array. Two people saving the same key at once means the last save wins. Keep each card, vote or player under its own key (cards/<id>, votes/<me>), and use add, increment and append, which are safe when people change things at the same time. Never read a whole board, change it and set it back.
  • Keys only use letters, digits and _ - . ~ : @ +, separated by /. No spaces, so cards/Buy milk is refused. Use the id add returns, or a slug.
  • subscribe tells you about other people’s changes, not your own. After a write succeeds, update the page yourself. The usual pattern is a render() that lists again, called after your own writes and from subscribe.
  • Live updates are only instant for people who are signed in. They get changes over a live connection within a second or two. Visitors on a share link without a session have no live connection: ShareCube checks the prefixes the page subscribed to every 30 seconds, so their changes can take up to about 45 seconds to show. A game or board that needs turns in real time should ask people to sign in, or say on the page that it refreshes every so often.
  • No alert, confirm, prompt or <form> submit. The page runs in a sandbox where the first three silently do nothing and a form’s submit event never fires, not even for event.preventDefault(). Use an input with a button’s click handler, and listen for Enter on the input. See what runs in an HTML page.
  • Say when saving isn’t available. In a template preview, or anywhere available is false, the page runs on data kept in memory that’s gone on reload. Show a short note rather than pretending it saved.
CallReturnsDoes
readya promise (a property, not a function)Resolves once the page is connected. Await it before anything else.
availabletrue or false (a property)Whether changes are actually saved. Read it after ready.
me()promise of an id, or nullThis person’s opaque id on this artifact, the <id> in users/<id> and in {self} rules. null without an account. Never a name.
get(key)promise of the value, or nullnull when there’s nothing there and when the rules hide it.
list(prefix)promise of an array of { key, value, updatedAt }Every entry whose key starts with prefix, all pages already fetched. list('') is everything you may see. Sort it yourself.
set(key, value)promise of the saved valueCreates or replaces. Values are any JSON.
update(key, fields)promise of the merged valueMerges fields into an existing object. Fails with not_found if the key doesn’t exist yet, so create it with set first.
increment(key, by)promise of the new numberAdds by (1 if left out), starting from 0 when the key is new. Safe when several people click at once.
append(key, items)promise of the new arrayAdds the items to the end of an array, creating it when the key is new. items is always an array.
delete(key)promise, no valueRemoves the entry.
add(collection, value)promise of the new idSaves value at collection/<new id> and returns the id. The best way to add cards, messages or RSVPs.
subscribe(prefix, fn)a function that stops it (not a promise)Calls fn when someone else changes something under prefix: within a second or two for people who are signed in, and within about 45 seconds for visitors without a session, whose page checks every 30 seconds. subscribe(fn) listens to everything.
can(op, key)true or false (not a promise)Whether this person may read, create, update or delete there, from the rules that apply to them. Use it to hide buttons people can’t use, and still handle a refused call: the server has the last word.

What subscribe passes to fn:

ChangeShape
An entry was saved{ key, value, updatedAt }
An entry was deleted{ key, deleted: true, updatedAt }
Read everything under prefix again (after a reconnect, or Delete all data){ reset: true, prefix }

Listing again on every change is the simplest correct way to handle all three.

A call that’s refused rejects with an Error whose code says why:

codeMeans
not_foundNothing there, or the rules don’t allow it. The two look the same on purpose, so a page can’t learn what it isn’t allowed to see.
invalid_argumentA bad key, a value that’s too large, or update given something that isn’t an object. The message says which.
conflictincrement on something that isn’t a number, append on something that isn’t an array, update on something that isn’t an object, or too many changes to one key at once (try again).
quota_exceededThe artifact holds as many entries or as much data as its plan allows.
rate_limitedToo many changes too quickly. Wait and try again.
read_onlyA version preview or a print, where nothing can be saved.
timeout, unavailableShareCube couldn’t be reached. Try again.

Every page with persistent state can start from this:

<p id="note" hidden>Changes here aren't saved.</p>
<ul id="list"></ul>
<div id="add"><input id="text" placeholder="Add an item"> <button id="add-button" type="button">Add</button></div>
<script>
const state = window.sharecube.state;
async function render() {
const items = await state.list('items/');
items.sort((a, b) => a.value.at.localeCompare(b.value.at));
document.getElementById('list').replaceChildren(...items.map(({ key, value }) => {
const li = document.createElement('li');
li.textContent = value.text;
if (state.can('delete', key)) {
const del = document.createElement('button');
del.textContent = 'Remove';
del.onclick = async () => { await state.delete(key); render(); };
li.append(' ', del);
}
return li;
}));
}
// Wired up straight away: every call waits for the connection by itself.
const input = document.getElementById('text');
async function addItem() {
if (!input.value.trim()) return;
try {
await state.add('items', { text: input.value, at: new Date().toISOString() });
input.value = '';
render();
} catch (err) {
showError(err);
}
}
document.getElementById('add-button').addEventListener('click', addItem);
input.addEventListener('keydown', (event) => { if (event.key === 'Enter') addItem(); });
state.subscribe('items/', render);
// `available` and `can()` only mean something once `ready` resolves.
state.ready.then(() => {
document.getElementById('note').hidden = state.available;
document.getElementById('add').hidden = !state.can('create', 'items/x');
render();
});
function showError(err) {
const note = document.getElementById('note');
note.hidden = false;
note.textContent = err.code === 'rate_limited' ? 'Slow down a little and try again.' : "That didn't save. Try again.";
}
</script>

Each card is its own entry, so two people moving different cards never overwrite each other. A card’s column and position are fields on the card.

  • Adding a card: const id = await state.add('cards', { title, column: 'todo', position: Date.now(), by: name }).
  • Moving a card: await state.update('cards/' + id, { column: 'doing', position: Date.now() }).
  • Showing the board: list('cards/'), group by value.column, then sort each column by value.position.
  • Live updates: subscribe('cards/', render).
  • Who did it: the page asks for a name once, keeps it at users/<me>/name (private to that person) and saves it on each card as by. me() alone can’t tell you anyone’s name.

No rules are needed when everyone with access should be able to add and move cards, since by default Commenters and up can change data. To let only Editors move cards, ask the agent for a rule like { "path": "cards", "write": "editor" }.

Each player’s best score lives under their own id, so they can’t change anyone else’s:

[
{ "path": "scores", "read": "viewer", "write": "none" },
{ "path": "scores/{self}", "write": "self" }
]
await state.ready;
const me = await state.me(); // an id, or null without an account
const saved = me ? await state.get('scores/' + me) : null;
// After a game:
if (me && score > (saved?.best ?? 0)) {
await state.set('scores/' + me, { best: score, name: playerName });
}
// The leaderboard:
const top = (await state.list('scores/')).sort((a, b) => b.value.best - a.value.best).slice(0, 10);

Game progress that only matters to one player, like the current level or settings, belongs under users/<me>/, which is private to them by default. Plain localStorage works for that too.

They mostly work as they are:

  • localStorage is kept per person, privately, and comes back the next time they open the page. For visitors who aren’t signed in it lasts only while the page is open.
  • window.storage (as in Claude’s artifacts) works, with shared values visible to everyone with access and personal ones private.
FreeProTeam
Entries per artifact1,0005,00025,000
Data per artifact5 MB20 MB100 MB
One value256 KB of JSON, nested at most 32 deep (16 KB and 8 deep from people without an account)
One key512 bytes, at most 16 segments of up to 200 bytes each
Changes60 a minute per person and 1,200 a minute per artifact. People without an account: 10 an hour from each visitor, and 300 an hour per artifact.
Rules64 per artifact
  • Editors can delete everything under Persistent state → Data → Delete all data. The page itself stays.
  • Deleting an artifact deletes its state.
  • When someone leaves an organization, their private data on its artifacts is deleted. Deleting an account deletes it everywhere.