Synced Store
The Synced Store provides real-time synchronized state for Canvas apps. Multiple users can collaborate on shared data that automatically syncs across all connected clients.
Quick Example
<script id="poe-store-config">
Poe.setupStore({
mutators: {
async setTodo(tx, { id, text, done }) {
await tx.table('todos').set(id, { id, text, done, updatedAt: Date.now() });
},
async deleteTodo(tx, { id }) {
await tx.table('todos').delete(id);
}
},
actions: {
async generateTodoWithAI(ctx, { prompt, botName }) {
const todoId = Date.now().toString();
const stream = Poe.stream({
bot: botName || 'Claude-Sonnet-4.6',
prompts: `Generate a single todo item based on: ${prompt}. Respond with just the todo text, nothing else.`
});
let todoText = '';
for await (const chunk of stream) {
todoText += chunk.text;
await ctx.mutate('setTodo', { id: todoId, text: todoText, done: false });
}
return { success: true, todoId, text: todoText.trim() };
}
}
});
</script>
<script>
// Use the store after setup
const store = window.Poe.store;
// Subscribe to changes
store.subscribe(
async (ctx) => await ctx.table('todos').entries().toArray(),
(todos) => renderTodos(todos)
);
// Add a todo manually
const id = Date.now().toString();
await store.mutate.setTodo({ id, text: 'Buy groceries', done: false });
// Or generate a todo with AI
const result = await store.action.generateTodoWithAI({
prompt: 'plan a birthday party'
});
console.log('Generated todo:', result.text);
</script>Overview
Key concepts:
- Mutators - Functions that modify data (the only way to write)
- Actions - Server-only operations that can call external APIs and orchestrate mutations
- Queries - One-time data reads
- Subscriptions - Reactive callbacks when data changes
API Methods
Poe.setupStore
Initialize the synced store with your mutator definitions. This must be called in a separate <script id="poe-store-config"> tag containing no other logic.
Signature
Poe.setupStore(options: {
mutators: {
[mutatorName: string]: (tx: WriteTransaction, args: JsonValue) => Promise<void>
},
actions?: {
[actionName: string]: (ctx: ActionContext, args: JsonValue) => Promise<JsonValue | void>
}
}): nullParameters
options.mutators(IMutators, required): Object containing all mutator functions for this storeoptions.actions(IActions, optional): Object containing all action functions for this store
Returns
A SyncedStore<T> instance that provides mutate, query, subscribe, and other methods. Also accessible via window.Poe.store.
Backend Execution
Important: The code inside <script id="poe-store-config"> runs on both the frontend AND backend. See Synced Store Limitations for constraints on what you can use in mutators.
Poe.store.mutate
Object containing all mutator functions. Mutators are the only way to modify store data. Poe.store.mutate cannot be called before Poe.setupStore.
Important: Each mutation is executed as a single database transaction. All operations within a mutator either succeed together or fail together, ensuring data consistency.
Signature
store.mutate: {
[K in keyof Mutators]: (arg: Parameters<Mutators[K]>[1]) => Promise<void>
}Example
// Define mutators in setupStore
Poe.setupStore({
mutators: {
async addUser(tx, { id, name, email }) {
await tx.table('users').set(id, { id, name, email });
},
async updateUserName(tx, { id, name }) {
const user = await tx.table('users').get(id);
if (!user) {
throw new Error(`User does not exist. (userId: ${id})`);
}
await tx.table('users').set(id, { ...user, name });
},
async deleteUser(tx, { id }) {
await tx.table('users').delete(id);
}
}
});
// Call mutators from your app
const store = window.Poe.store;
const userId = crypto.randomUUID();
await store.mutate.addUser({
id: userId,
name: 'John',
email: '[email protected]'
});
await store.mutate.updateUserName({ id: userId, name: 'Jane' });
await store.mutate.deleteUser({ id: userId });Poe.store.action
Object containing all action functions. Actions are server-only operations that can orchestrate multiple mutations, call external APIs (like Poe.stream), and return results to the client. Unlike mutators, actions do NOT run optimistically on the client.
Signature
store.action: {
[K in keyof Actions]: (input: Parameters<Actions[K]>[1]) => Promise<ReturnType<Actions[K]>>
}Key Differences from Mutators
| Feature | Mutators | Actions |
|---|---|---|
| Execution | Client (optimistic) + Server | Server only |
| Return Value | No return value | Can return JSON values |
| Database Access | Read + Write via tx.table() | Read via ctx.table(), Write via ctx.mutate() |
| External APIs | ❌ Not recommended | ✅ Designed for this |
| Use Case | Quick, single data writes | Long running requests, API calls |
ActionContext
Actions receive an ActionContext as the first parameter:
type ActionContext = {
userId: string; // Current user ID
clientId: string; // Current client ID
isServer: boolean; // Always true for actions
table: (tableName: string) => TableReader; // Read from tables
mutate: (mutatorName: string, input: any) => Promise<void>; // Write via mutations
}Example: Action Using Poe.stream
Actions can use Poe.stream() to call AI bots and progressively write results to the store. The message text is accumulated and written as it streams:
Poe.setupStore({
mutators: {
async updateMessage(tx, { messageId, text, complete }) {
await tx.table('messages').set(messageId, {
text,
complete,
updatedAt: Date.now()
});
}
},
actions: {
// Stream AI response and update message as chunks arrive
async streamBotResponse(ctx, { prompt, botName }) {
// Use Date.now() for message ID so messages are naturally sorted
const messageId = Date.now().toString();
const stream = Poe.stream({
bot: botName,
prompts: prompt
});
let accumulatedText = '';
let chunkCount = 0;
// Process each chunk as it arrives
for await (const chunk of stream) {
accumulatedText += chunk.text;
chunkCount++;
// Update the message with accumulated text (not yet complete)
await ctx.mutate('updateMessage', {
messageId,
text: accumulatedText,
complete: false
});
}
// Mark message as complete
await ctx.mutate('updateMessage', {
messageId,
text: accumulatedText,
complete: true
});
return {
success: true,
messageId,
chunkCount,
totalLength: accumulatedText.length
};
}
}
});
// Usage in your app
const store = window.Poe.store;
// Subscribe to see the message update in real-time as chunks arrive
store.subscribe(
async (ctx) => {
const messages = await ctx.table('messages').entries().toArray();
// Messages are naturally sorted by ID (timestamp)
return messages.map(([id, msg]) => msg);
},
(messages) => {
const messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML = messages.map(msg => `
<div class="message ${msg.complete ? 'complete' : 'streaming'}">
${msg.text}
${msg.complete ? '' : '<span class="cursor">▊</span>'}
</div>
`).join('');
}
);
// Start the streaming action
const result = await store.action.streamBotResponse({
prompt: 'Write a short poem about the ocean',
botName: 'Claude-Sonnet-4.6'
});
console.log(`Message ${result.messageId}: received ${result.chunkCount} chunks`);When to Use Actions vs Mutators
Use Mutators for:
- Quick, transaction data modifications
- Operations that benefit from optimistic updates Use Actions for:
- Calling external APIs or
Poe.stream() - Complex orchestration of multiple mutations
- Operations that need to return results to the client
- Non-deterministic operations (API calls, streaming)
Poe.store.query
Execute a read-only query against the store. Use for one-time data reads.
Note: store.query only works on the client. It is not available on the server (i.e., inside actions or mutators).
Signature
Poe.store.query<T>(
queryFn: (ctx: ReadTransaction) => Promise<T>
): Promise<T>Parameters
queryFn(function, required): Function that receives aReadTransactionand returns the query result
Returns
Promise resolving to the query result.
Example: Get Single Item
const user = await store.query(async (ctx) => {
return await ctx.table('users').get('user-123');
});
if (user) {
console.log('Found user:', user.name);
}Example: Get All Items
const allUsers = await store.query(async (ctx) => {
return await ctx.table('users').entries().toArray();
});
// Returns: [['user-123', { name: 'John', ... }], ['user-456', { name: 'Jane', ... }]]Example: Scan with Prefix
const adminUsers = await store.query(async (ctx) => {
return await ctx.table('users')
.scan({ prefix: 'admin_' })
.entries()
.toArray();
});Poe.store.subscribe
Subscribe to changes in the store. The callback is called initially and whenever data changes. Use for reactive UI updates.
Note: store.subscribe only works on the client. It is not available on the server (i.e., inside actions or mutators).
Signature
store.subscribe<T>(
queryFn: (ctx: ReadTransaction) => Promise<T>,
onChange: (value: T) => void
): UnsubscribeFnParameters
queryFn(function, required): Function that receives aReadTransactionand returns the subscribed valueonChange(function, required): Callback invoked with the new value whenever it changes
Returns
A function to unsubscribe from changes.
Note: Subscriptions Fire Twice Per Mutation
For each mutation, subscriptions may fire twice:
- Optimistic update - Immediately when the mutation runs on the client
- Server confirmation - Again when the authoritative server response arrives
Design your onChange callback to handle being called multiple times with the same or similar data.
Example: Subscribe to Single Value
const unsubscribe = store.subscribe(
async (ctx) => await ctx.table('users').get('user-123'),
(user) => {
if (user) {
document.getElementById('username').textContent = user.name;
}
}
);
// Later: stop listening
unsubscribe();Example: Subscribe to List
const unsubscribe = store.subscribe(
async (ctx) => await ctx.table('todos').entries().toArray(),
(entries) => {
const todos = entries.map(([id, todo]) => ({ id, ...todo }));
renderTodoList(todos);
}
);Example: Subscribe to Computed Value
// Subscribe to count of completed todos
const unsubscribe = store.subscribe(
async (ctx) => {
const entries = await ctx.table('todos').entries().toArray();
return entries.filter(([_, todo]) => todo.done).length;
},
(completedCount) => {
document.getElementById('completed').textContent = `${completedCount} done`;
}
);Poe.store.subscribeToTable
Subscribe to all changes in a specific table with detailed change information.
Note: store.subscribeToTable only works on the client. It is not available on the server (i.e., inside actions or mutators).
Signature
Poe.store.subscribeToTable(
tableName: string,
onChange: (
entries: [string, JSONValue][],
changes: {
added: [string, JSONValue][],
modified: [string, JSONValue][],
removed: [string, JSONValue][]
}
) => void
): UnsubscribeFnParameters
tableName(string, required): Name of the table to monitoronChange(function, required): Callback with current entries and detailed changes
Returns
A function to unsubscribe from table changes.
Example
const unsubscribe = Poe.store.subscribeToTable('messages', (entries, changes) => {
// All current messages
console.log('All messages:', entries);
// What changed
if (changes.added.length > 0) {
console.log('New messages:', changes.added);
playNotificationSound();
}
if (changes.modified.length > 0) {
console.log('Edited messages:', changes.modified);
}
if (changes.removed.length > 0) {
console.log('Deleted messages:', changes.removed);
}
});Poe.store.waitUntilReady
Wait for the store to complete initial synchronization with the server.
Signature
Poe.store.waitUntilReady(): Promise<void>Example
// Wait for initial sync before rendering
await Poe.store.waitUntilReady();
// Now safe to query
const data = await Poe.store.query(async (ctx) => {
return await ctx.table('settings').get('config');
});
renderApp(data);Poe.store.onFailedMutation
Register a callback to be notified when a mutation is discarded after the initial optimistic call. This happens when a mutation succeeds on the client but is later rejected by the server, causing the optimistic update to be rolled back.
Note: If a mutation fails during the initial call (e.g., the mutator throws an error), the error is thrown directly to the caller and onFailedMutation is not triggered.
Signature
Poe.store.onFailedMutation(
callback: (info: FailedMutationInfo) => void
): UnsubscribeFnParameters
callback(function, required): Function called when a mutation fails, receiving details about the failure
Returns
A function to unsubscribe from failure notifications.
FailedMutationInfo
type FailedMutationInfo = {
mutation: {
name: string; // The mutator function name
args: JSONValue; // The arguments passed to the mutator
};
error: {
errorType: MutationFailureType; // The type of failure
message: string; // Human-readable error message
};
}MutationFailureType
| Value | Description |
|---|---|
KEY_TOO_LARGE | The key exceeds the 512 KB limit |
VALUE_TOO_LARGE | The serialized value exceeds the 1 MB limit |
TOTAL_DATABASE_SIZE_EXCEEDED | The total database size exceeds the 10mb limit |
OPTIMISTIC_LOCK_RETRY_LIMIT_EXCEEDED | The mutation failed due to optimistic lock conflicts after exhausting retries |
MUTATOR_THREW_AN_ERROR | The user defined mutator logic threw an error |
SYNCED_STORE_INTERNAL_ERROR | Internal error in the synced store (should never occur - indicates a Poe bug) |
UNKNOWN | Unknown error (should never occur - might indicate a network outage or a Poe bug) |
Example
// Register handler for failed mutations
const unsubscribe = store.onFailedMutation((info) => {
console.error(`Mutation "${info.mutation.name}" failed:`, info.error.message);
// Show user-friendly error based on type
switch (info.error.errorType) {
case 'VALUE_TOO_LARGE':
showToast('The data is too large to save. Please reduce the size.');
break;
case 'MUTATOR_THREW_AN_ERROR':
showToast(info.error.message);
break;
default:
showToast('Failed to save changes. Please try again.');
}
});
// Later: stop listening
unsubscribe();When This Callback Is Triggered
This callback is triggered when a mutation passes the initial optimistic execution but is later rejected by the server:
- Size limits exceeded - Key or value too large (detected on server)
- Server-side validation errors - Mutator threw an error on the server that didn't occur on the client
- Optimistic lock conflicts - After exhausting retries, the mutation is reverted
When triggered, the optimistic update made on the client is rolled back, and subscriptions are notified of the reverted state.
See Why Mutations Might Fail for more details.
Transaction Types
ReadTransaction
Read-only transaction context provided to query and subscribe callbacks.
type ReadTransaction = {
userId: string;
clientId: string;
isServer: boolean;
table: (tableName: string) => TableReader;
}Table Read Operations
| Method | Description |
|---|---|
get(key) | Get a single value by key |
has(key) | Check if key exists |
scan(options?) | Scan for entries with optional prefix/limit |
entries() | Get all key-value pairs |
keys() | Get all keys |
values() | Get all values |
await store.query(async (ctx) => {
const table = ctx.table('users');
// Get single value
const user = await table.get('user-123');
// Check existence
const exists = await table.has('user-123');
// Scan with options
const results = await table.scan({
prefix: 'admin_',
limit: 10
}).entries().toArray();
// Get all entries
const all = await table.entries().toArray();
});WriteTransaction
Write transaction context provided to mutator functions. Extends ReadTransaction with write operations.
type WriteTransaction = ReadTransaction & {
table: (tableName: string) => TableWriter;
}Table Write Operations
| Method | Description |
|---|---|
set(key, value) | Store a value at key (overwrites entire value, does not merge) |
delete(key) | Remove entry at key |
Important: set() completely replaces the value at a key. To update specific fields while preserving others, read the existing value first:
Poe.setupStore({
mutators: {
// Overwrites entire record - previous fields are lost
async setUserName(tx, { userId, name }) {
await tx.table('users').set(userId, { name });
},
// Preserves existing fields by reading first
async updateUserName(tx, { userId, name }) {
const user = await tx.table('users').get(userId);
if (!user) {
throw new Error(`User does not exist. (userId: ${userId})`);
}
await tx.table('users').set(userId, { ...user, name });
},
async removeUser(tx, { userId }) {
await tx.table('users').delete(userId);
}
}
});Complete Example: Collaborative Todo App
<!DOCTYPE html>
<html>
<head>
<title>Collaborative Todos</title>
</head>
<body>
<h1>Todos</h1>
<input type="text" id="new-todo" placeholder="Add a todo...">
<button id="add-btn">Add</button>
<ul id="todo-list"></ul>
<!-- Store configuration - must have id="poe-store-config" -->
<script id="poe-store-config">
Poe.setupStore({
mutators: {
async addTodo(tx, { id, text }) {
await tx.table('todos').set(id, {
id,
text,
done: false,
createdAt: Date.now()
});
},
async toggleTodo(tx, { id, done }) {
const todo = await tx.table('todos').get(id);
if (!todo) {
throw new Error(`Todo does not exist. (todoId: ${id})`);
}
await tx.table('todos').set(id, { ...todo, done });
},
async deleteTodo(tx, { id }) {
await tx.table('todos').delete(id);
}
}
});
</script>
<!-- App logic -->
<script>
const store = window.Poe.store;
const todoList = document.getElementById('todo-list');
const input = document.getElementById('new-todo');
const addBtn = document.getElementById('add-btn');
// Subscribe to todos and re-render on changes
store.subscribe(
async (ctx) => await ctx.table('todos').entries().toArray(),
(entries) => {
const todos = entries
.map(([id, todo]) => ({ id, ...todo }))
.sort((a, b) => a.createdAt - b.createdAt);
todoList.innerHTML = todos.map(todo => `
<li>
<input type="checkbox"
${todo.done ? 'checked' : ''}
onchange="toggleTodo('${todo.id}', this.checked)">
<span style="${todo.done ? 'text-decoration: line-through' : ''}">
${todo.text}
</span>
<button onclick="deleteTodo('${todo.id}')">Delete</button>
</li>
`).join('');
}
);
// Add todo handler
addBtn.onclick = async () => {
const text = input.value.trim();
if (!text) return;
const id = crypto.randomUUID();
await store.mutate.addTodo({ id, text });
input.value = '';
};
// Toggle todo handler
window.toggleTodo = async (id, done) => {
await store.mutate.toggleTodo({ id, done });
};
// Delete todo handler
window.deleteTodo = async (id) => {
await store.mutate.deleteTodo({ id });
};
</script>
</body>
</html>Type Definitions
SyncedStore
type SyncedStore<Mutators extends IMutators, Actions extends IActions = {}> = {
mutate: { [K in keyof Mutators]: (input: Parameters<Mutators[K]>[1]) => Promise<void> };
action: { [K in keyof Actions]: (input: Parameters<Actions[K]>[1]) => Promise<ReturnType<Actions[K]>> };
query: <T>(queryFn: (ctx: ReadTransaction) => Promise<T>) => Promise<T>;
subscribe: <T>(queryFn: (ctx: ReadTransaction) => Promise<T>, onChange: (value: T) => void) => UnsubscribeFn;
subscribeToTable: (tableName: string, onChange: (entries: [string, JSONValue][], changes: TableChanges) => void) => UnsubscribeFn;
waitUntilReady: () => Promise<void>;
onFailedMutation: (callback: (info: FailedMutationInfo) => void) => UnsubscribeFn;
}IMutators
type IMutators = Record<string, (tx: WriteTransaction, input: any) => Promise<void>>IActions
type IActions = Record<string, (ctx: ActionContext, input: any) => Promise<JSONValue | void>>ActionContext
type ActionContext = {
userId: string;
clientId: string;
mutate: (mutatorName: string, input: JSONValue) => Promise<void>;
}JSONValue
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }UnsubscribeFn
type UnsubscribeFn = () => voidFailedMutationInfo
type FailedMutationInfo = {
mutation: {
name: string;
args: JSONValue;
};
error: {
errorType: MutationFailureType;
message: string;
};
}
enum MutationFailureType {
KEY_TOO_LARGE = "KEY_TOO_LARGE",
VALUE_TOO_LARGE = "VALUE_TOO_LARGE",
TOTAL_DATABASE_SIZE_EXCEEDED = "TOTAL_DATABASE_SIZE_EXCEEDED",
OPTIMISTIC_LOCK_RETRY_LIMIT_EXCEEDED = "OPTIMISTIC_LOCK_RETRY_LIMIT_EXCEEDED",
MUTATOR_THREW_AN_ERROR = "MUTATOR_THREW_AN_ERROR",
SYNCED_STORE_INTERNAL_ERROR = "SYNCED_STORE_INTERNAL_ERROR",
UNKNOWN = "UNKNOWN",
}See Also
- Synced Store Limitations - Constraints and pitfalls
- Poe Embed API - Core Canvas app API
- Canvas Apps Overview - Getting started with Canvas apps