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.
Where to find it
Section titled “Where to find it”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.
Rules and permissions
Section titled “Rules and permissions”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.
Your level
Section titled “Your level”What you can do depends on your level on the artifact, which comes from how you reached it:
| You are | Your 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 Owner | Creator, above Editor |
| A Commenter, or in your organization and in through a link set to Commenter | Commenter |
| A Viewer, or in your organization and in through a link set to Viewer | Viewer |
| Not signed in, or signed in to another organization and in only through the public link | Anyone |
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.
The defaults
Section titled “The defaults”Every artifact has these two rules, and its own rules sit on top of them:
| Path | See | Add, change, delete |
|---|---|---|
| Everything | Viewers and up | Commenters and up |
users/<each person> | Only that person | Only 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.
What a rule looks like
Section titled “What a rule looks like”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" }]| Field | Meaning |
|---|---|
path | The part of the data the rule covers, like votes or tasks/done. "" means everything. |
read | Who can see entries there. |
create | Who can add new entries. |
update | Who can change existing entries. |
delete | Who can delete entries. |
write | Shorthand for create, update and delete together. Any of the three set on its own wins over it. |
max | At 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:
| Level | Who |
|---|---|
anyone | Anyone with the link, signed in or not. Counts only while the artifact is public. |
viewer | Viewers and up. |
commenter | Commenters and up. |
editor | Editors and up (Owners included). |
creator | Only the artifact’s creator. |
self | Only the person the entry belongs to. Only on a path ending in {self}. |
none | No one. |
Which rule applies
Section titled “Which rule applies”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
tasksrule doesn’t say, so the default for everything applies: Viewers and up. - add, change, delete: the
tasksrule 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.
Each person’s own space: {self}
Section titled “Each person’s own space: {self}”{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.
What ShareCube refuses
Section titled “What ShareCube refuses”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. selfon a path that doesn’t end in{self},{self}anywhere but the end of a path, or{self}on its own.maxon 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.
Who can see and change the rules
Section titled “Who can see and change the rules”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.
Examples
Section titled “Examples”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" }]Choosing rules for a page
Section titled “Choosing rules for a page”This part is for the agent building the page. Decide the keys first, then the rules that fit them.
- 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. - 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. - Read the current rules with
get_artifact_state_rules. - 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. - 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. - 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 page | Keys | Rules |
|---|---|---|
| Shared checklist or team kanban board | tasks/<id>, cards/<id> | None |
| Same, but Viewers can move cards too | cards/<id> | [{ "path": "cards", "write": "viewer" }] |
| Same, but only Editors change the board | cards/<id> | [{ "path": "cards", "write": "editor" }] |
| Poll: one vote each, everyone sees the tally | votes/<me> | [{ "path": "votes", "read": "viewer", "write": "editor" }, { "path": "votes/{self}", "write": "self" }] |
| Game leaderboard: each player sets only their own score | scores/<me> | [{ "path": "scores", "read": "viewer", "write": "none" }, { "path": "scores/{self}", "write": "self" }] |
| Survey: each person sees only their own answers, Editors see all | answers/<me> | [{ "path": "answers", "read": "editor", "write": "editor" }, { "path": "answers/{self}", "read": "self", "write": "self" }] |
| Personal progress or settings | users/<me>/... | None |
| Public RSVP that guests can’t read | rsvps/<id> from add | [{ "path": "rsvps", "read": "editor", "create": "anyone", "update": "none", "delete": "editor", "max": 200 }] (pending until confirmed) |
| Public guestbook everyone can read | guestbook/<id> from add | [{ "path": "guestbook", "read": "anyone", "create": "anyone", "update": "none", "delete": "editor", "max": 500 }] (pending until confirmed) |
| Settings only the creator changes | config/... | [{ "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 becauseupdateanddeletewould 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 bothreadandwrite, 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 withRule "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 inlocalStorage, 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.
People without an account
Section titled “People without an account”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
Section titled “Agents”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.
Building a page with persistent state
Section titled “Building a page with persistent state”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.
Before you start
Section titled “Before you start”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 like7f3ac1d29e0b44a1, 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’snullfor 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
readyonce, before anything else.await sharecube.state.ready, then readsharecube.state.available. Beforereadyresolves,availableisfalseandcan()answersfalsefor everything. can()is the one call that isn’t async. It returnstrueorfalsestraight away, so call it afterreadyand don’tawaitit.- 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 useadd,incrementandappend, which are safe when people change things at the same time. Never read a whole board, change it andsetit back. - Keys only use letters, digits and
_ - . ~ : @ +, separated by/. No spaces, socards/Buy milkis refused. Use the idaddreturns, or a slug. subscribetells you about other people’s changes, not your own. After a write succeeds, update the page yourself. The usual pattern is arender()that lists again, called after your own writes and fromsubscribe.- 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,promptor<form>submit. The page runs in a sandbox where the first three silently do nothing and a form’ssubmitevent never fires, not even forevent.preventDefault(). Use an input with a button’sclickhandler, 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
availableisfalse, the page runs on data kept in memory that’s gone on reload. Show a short note rather than pretending it saved.
The API
Section titled “The API”| Call | Returns | Does |
|---|---|---|
ready | a promise (a property, not a function) | Resolves once the page is connected. Await it before anything else. |
available | true or false (a property) | Whether changes are actually saved. Read it after ready. |
me() | promise of an id, or null | This 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 null | null 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 value | Creates or replaces. Values are any JSON. |
update(key, fields) | promise of the merged value | Merges 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 number | Adds 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 array | Adds the items to the end of an array, creating it when the key is new. items is always an array. |
delete(key) | promise, no value | Removes the entry. |
add(collection, value) | promise of the new id | Saves 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:
| Change | Shape |
|---|---|
| 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.
Errors
Section titled “Errors”A call that’s refused rejects with an Error whose code says why:
code | Means |
|---|---|
not_found | Nothing 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_argument | A bad key, a value that’s too large, or update given something that isn’t an object. The message says which. |
conflict | increment 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_exceeded | The artifact holds as many entries or as much data as its plan allows. |
rate_limited | Too many changes too quickly. Wait and try again. |
read_only | A version preview or a print, where nothing can be saved. |
timeout, unavailable | ShareCube couldn’t be reached. Try again. |
A starting point
Section titled “A starting point”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>Example: a kanban board
Section titled “Example: a kanban board”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 byvalue.column, then sort each column byvalue.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 asby.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" }.
Example: a game with a leaderboard
Section titled “Example: a game with a leaderboard”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 accountconst 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.
Pages written for other tools
Section titled “Pages written for other tools”They mostly work as they are:
localStorageis 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.
Limits
Section titled “Limits”| Free | Pro | Team | |
|---|---|---|---|
| Entries per artifact | 1,000 | 5,000 | 25,000 |
| Data per artifact | 5 MB | 20 MB | 100 MB |
| One value | 256 KB of JSON, nested at most 32 deep (16 KB and 8 deep from people without an account) |
| One key | 512 bytes, at most 16 segments of up to 200 bytes each |
| Changes | 60 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. |
| Rules | 64 per artifact |
Deleting state
Section titled “Deleting state”- 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.