Server data
Data
octane/data loads and caches data from your server and saves edits back to it. You describe each read and write once. Components, pages and tabs can then share the same values, even while an edit is pending or being rolled back.
Say you're building a reading list. When someone marks a book as finished, you want the change to show up wherever that book appears, even in another tab. The checkbox should tick right away, though you'll need to undo the edit if the server turns it down. And when the reader leaves the list and comes back, you'd like to show the books you already loaded and check for a newer copy if the list is stale.
With octane/data, you describe how to read the list and what it means to
mark a book as finished. A store handles the requests and keeps track of
both the books the server has confirmed and the edits you're waiting on.
Its cache outlives any one component. On a server-rendered page, the browser
can pick up the server's copy of the list during hydration and save a second
request. The store works independently of any renderer, so you can use it
from Octane, React or plain TypeScript, including your tests.
The reading list is a good fit for octane/data because the server owns the
records and several parts of the app read and edit them. For state your app
owns, like a draft or the selected tab, or for a one-off async value, use
Signals. Best practices
has more advice on working with contracts, stores and writes.
How the pieces fit
With octane/data, there are six parts to getting a book from the server
onto the page. You'll use all six in the first example.
- A contract describes an operation. A read loads data, a write changes it, a view defines a sorted list and a feed describes a stream of server events. Importing a contract makes no requests, so the browser, the server and your tests can all import the same definition.
- A store runs these operations in the browser. If two components ask for the reading list, the store makes one request and caches the result for both. It also applies edits as soon as you make them and undoes them if the server refuses the write.
- A data worker does the store's work that doesn't have to happen on the page. It makes each request, checks each reply against its contract, and holds the feed connections and the cache, all off the page's main thread. Tabs signed in to the same account share one data worker.
- A transport is the function the data worker calls to reach the server.
It might use
fetch, call amodule serverfunction or send the request another way. - A handler on the server matches each contract to the function you wrote for it. It checks the input before passing it to your function.
- A binding gives your components hooks for working with the store.
octane/data/octaneandoctane/data/reactprovide the same hooks for their respective renderers.
- Contractsread, write, view, feed
- ComponentsuseRead, useForm
- Storecache, edits, rollback
- Data workerrequests, validation, feeds
- TransportserverTransport or httpTransport
- HandlercreateDataHandler validates and runs
The entry points let you import just the parts a page needs, so the rest can stay out of its bundle.
| Entry point | What it holds | Where it runs |
|---|---|---|
octane/data | Contracts, the store, transports, feeds, persistence, and cross-tab sharing | Browser and server |
octane/data/server | createDataHandler, which serves contracts | Server only |
octane/data/manifest | Your app's contracts, writes and identity, generated by the build | Browser and server |
octane/data/client | openDataStore(account, options?), generated by the build from your data client | Browser and server |
octane/data/octane | The Octane binding, including DataProvider, useRead and the other hooks | Octane components |
octane/data/react | The React binding, with the same names and behavior | React components |
You can import the Octane hooks from octane/data/octane in a component
that renders on the server, too. The compiler selects the server version
of the binding when it builds the component for a server render.
Your first read
Let's start with the part of the reading list that loads the books and shows their titles. We'll follow the data from the contract through to the component in four steps.
1. Describe the data
Both ends of the request need to agree on what a book looks like. The
contract uses a schema to check that each value has the shape you expect.
These examples use Zod. You can use octane/data with any validator that
implements Standard Schema, including Valibot
and ArkType.
// contracts.data.ts — imported by the server and by the browser.
import { read } from 'octane/data';
import { z } from 'zod';
export const Book = z.object({
id: z.string(),
title: z.string().trim().min(1, 'Enter a title'),
read: z.boolean(),
});
export type Book = z.infer<typeof Book>;
export const books = read({
name: 'books.list',
output: z.array(Book),
});The server uses the read's unique name, books.list, to find the function
that serves it. The output schema says that function returns an array of
books. A read can also declare an input, as we'll do when we look up a
book by ID.
In the examples that follow, the contract declarations belong in
contracts.data.ts. The .data.ts suffix lets the build
check every contract.
2. Serve it
On the server, use createDataHandler to associate the books contract
with a function that returns the contents of the shelf. For each contract,
the handler checks the input against its schema before calling your
function and checks the output before sending it back.
// server.ts — server code only.
import { createDataHandler } from 'octane/data/server';
import { books, type Book } from './contracts.data.ts';
const shelf: Book[] = [
{ id: '1', title: 'Kindred', read: false },
{ id: '2', title: 'Piranesi', read: true },
];
export const handler = createDataHandler({}, (handle) => [handle(books, () => shelf)]);The first argument is for options, such as how to identify the signed-in user. In the second, you list the handlers that use those options. This order lets TypeScript infer the types your handlers receive, as you'll see in Serve your contracts.
The browser still needs a way to call handler. In an Octane app, the
simplest approach is to export a function from a module server block.
The function runs on the server. In the browser you call it like a local
function, and a small stub generated by the compiler sends the request
through your app's origin checks and middleware.
// data.tsrx — the one door between the store and the handler.
module server {
import type { ServerCallContext } from 'octane/server';
import { handler } from './server.ts';
export async function data(request: string, call: ServerCallContext) {
return handler.serve(request, call);
}
}
import { data } from 'server';
export { data };handler.serve answers one request from the store. If your app uses a plain
HTTP endpoint, see Serve over HTTP.
3. Create a store
The store lives in the page, but it hands its requests to a data worker, so loading and checking the shelf never competes with rendering it. You describe how to reach the server once, in a data client module, and the build makes the worker and the page's store from it.
The data client. Its default export is defineDataClient with the
transport, here serverTransport(data), which sends each request through the
data function we just wrote.
// data.client.ts
import { defineDataClient, serverTransport } from 'octane/data';
import { data } from './data.tsrx';
export default defineDataClient({ transport: serverTransport(data) });The build option. Set dataClient to the path of that module. The plugin
generates the data worker from it and emits it at /_octane/data-worker.js
across deploys, so tabs opened before and after a deploy use the same worker
URL. The dev server serves it there too. In Vite, you can set the option on
the compiler plugin from octane/compiler/vite or on octane() from
@octanejs/vite-plugin.
// vite.config.ts
import { defineConfig } from 'vite';
import { octane } from 'octane/compiler/vite';
export default defineConfig({
plugins: [octane({ dataClient: 'src/data.client.ts' })],
});With Rspack, set dataClient on @octanejs/rspack-plugin. It emits a
separate entry named octane-data-worker; leave that entry out of your
pages' HTML.
// rspack.config.mjs
import { OctaneRspackPlugin } from '@octanejs/rspack-plugin';
export default {
plugins: [new OctaneRspackPlugin({ dataClient: './src/data.client.ts' })],
};The store. The build also generates octane/data/client. Its
openDataStore(account) opens the store of the signed-in account, named by
its ID, such as the user's ID.
// store.ts
import { openDataStore } from 'octane/data/client';
import { session } from './session.ts';
export const store = openDataStore(session.account);Every tab that passes the same account ID connects to the same worker, so
the shelf loads once however many tabs show it. The worker checks what the
server sends against your contracts' schemas, taken from the generated
octane/data/manifest, before it reaches the page.
Where a browser has no SharedWorker, as in Chrome on Android, the tab runs
the same worker as one of its own. If no worker can start, or the worker
can't serve this tab, the store makes its requests itself with the same
transport, so the shelf still works. Sharing across tabs covers
when that happens.
Create a store for each signed-in account and reuse it for as long as that account is signed in. The cache belongs to the store, so every new store starts with an empty one.
Where there's no page to keep free, such as on the server, in a test or in a
script, create a plain store with createDataStore({ transport }) instead.
It does all its work where it runs. The rest of this guide uses
createDataStore to show a store's options. In the browser, transport,
listen and persist go in the data client, and the page's own options,
such as a server render's seed, go to openDataStore(account, { seed }).
4. Show it in a component
Put a DataProvider near the top of your app and pass it the store. Any
component below the provider can get that store with useDataStore().
Here BookList passes the result of store.read(books) to useRead
to get the list to render.
// App.tsrx
import { DataProvider, useDataStore, useRead } from 'octane/data/octane';
import { books } from './contracts.data.ts';
import { store } from './store.ts';
function BookList() @{
const list = useRead(useDataStore().read(books));
<ul>
@for (const book of list; key book.id) {
<li>{book.title as string}</li>
} @empty {
<li>The shelf is empty.</li>
}
</ul>
}
export function App() @{
<DataProvider store={store}>
@try {
<BookList />
} @pending {
<p>Loading the shelf…</p>
} @catch (error) {
<p role="alert">{`Could not load the shelf: ${(error as Error).message}` as string}</p>
}
</DataProvider>
}Calling store.read(books) gives you a handle for the read. The
store returns the same handle for the same read and input, so you can
ask for it on every render. Outside a component you can use the handle
to get a snapshot, subscribe to changes or refresh the list. Here,
useRead manages the subscription for as long as BookList is mounted.
By the time useRead returns, list is an array of books. While it's
waiting for that first array, the hook suspends, so the nearest
@pending arm (or <Suspense> boundary) shows the loading message. If
the first load fails, the hook throws the error to the nearest @catch
or error boundary. On later reloads there are already books to show, so
they stay on screen while the request runs.
To render the list in React, import the hooks from the React binding and write the component in JSX. The call that reads the books is the same.
/** @jsxImportSource react */
// App.tsx
import { Suspense } from 'react';
import { DataProvider, useDataStore, useRead } from 'octane/data/react';
import { books } from './contracts.data.ts';
import { store } from './store.ts';
function BookList() {
const list = useRead(useDataStore().read(books));
if (list.length === 0) return <p>The shelf is empty.</p>;
return (
<ul>
{list.map((book) => (
<li key={book.id}>{book.title}</li>
))}
</ul>
);
}
export function App() {
return (
<DataProvider store={store}>
<Suspense fallback={<p>Loading the shelf…</p>}>
<BookList />
</Suspense>
</DataProvider>
);
}We'll use that same path for the rest of the guide. The contract describes the data, the handler serves it, and the hook reads it from the store.
Reading data
Reads with an input
So far we've asked for every book on the shelf. To look up one book by ID,
give the read an input schema and pass the ID in the second argument to
store.read. The same pattern works for a search term or any other
argument your read needs.
import { read } from 'octane/data';
import { z } from 'zod';
export const book = read({
name: 'books.byId',
input: z.object({ id: z.string() }),
output: z.object({ id: z.string(), title: z.string(), read: z.boolean() }),
});import { useDataStore, useRead } from 'octane/data/octane';
import { book } from './contracts.data.ts';
export function BookTitle(props: { id: string }) @{
const value = useRead(useDataStore().read(book, { id: props.id }));
<h1>{value.title as string}</h1>
}The store uses the read's name and input together as the cache key.
Two components asking for book with { id: '1' } share a request and a
cached value. Asking for { id: '2' } gives you a separate entry. The
store compares inputs by value, so you can write the object literal right
in the component, even though that creates a new object on each render.
Read without suspending
You might want the book count beside the list to show its own loading
message. Pass { suspend: false } to useRead to handle loading and
errors within the component. The hook stays subscribed and returns the
handle's snapshot, which includes both the value and the status of
the read.
import { useDataStore, useRead } from 'octane/data/octane';
import { books } from './contracts.data.ts';
export function ShelfCount() @{
const snapshot = useRead(useDataStore().read(books), { suspend: false });
<p>
@if (snapshot.status === 'pending') {
<span>Counting…</span>
} @else if (snapshot.status === 'error') {
<span>Count unavailable</span>
} @else {
<span>{`${snapshot.value!.length} books${snapshot.refreshing ? ' (updating)' : ''}`}</span>
}
</p>
}The count uses status to decide what to display and refreshing to
show when an update is underway. Here's what you can read from a snapshot.
| Field | Meaning |
|---|---|
status | Starts as 'pending' and becomes 'ready' when a value arrives or 'error' if the first load fails. |
value | The latest value from the server, including any edits you're waiting for it to confirm. |
error | The reason the load failed, when status is 'error'. |
refreshing | The store is reloading the value while showing the current one. |
stale | The value has aged past its freshness limit or a write marked it stale. |
more | For a view, there are more rows after the ones you see. |
preview | The load is still underway and value holds a provisional result. |
Show cached data while fetching is paused
Suppose you're moving book titles to a new loader. While it starts up, keep
reading the same book ID from the signed-in account's store. In Octane and
React, pass the loader's readiness to fetch.
import { useDataStore, useRead } from 'octane/data/octane';
import { book } from './contracts.data.ts';
export function useBook(id: string, loaderReady: boolean) {
const handle = useDataStore().read(book, { id });
return useRead(handle, { suspend: false, fetch: loaderReady });
}With fetch: false, the snapshot shows the cached book, including a copy
restored from storage. A cache miss starts out pending. Another reader or
an explicit handle.refresh() can fetch the book, and this snapshot receives
the result. When loaderReady becomes true, the store fetches if the
book is missing or needs a refresh.
Use this option while the account still has access to the book. If access ends, stop rendering the book. Retire the store when the account signs out.
Show results as they arrive
A search can show its first matches while the server is still refining
the results. As each batch arrives, the transport can give the store a
preview of the results so far. If the read has no confirmed value yet,
its snapshot becomes ready with the latest results and preview set to
true. The final reply replaces the preview in a single update, so the
list stays on screen throughout.
You supply the code that makes the request and parses the stream. In this
transport, searchStream does that work for the search read, and all
other requests go through httpTransport.
import { httpTransport, type Transport } from 'octane/data';
import { search } from './contracts.data.ts';
import { searchStream } from './search-stream.ts';
const http = httpTransport('/api/data');
export const transport: Transport = async (request, signal, preview) => {
if (request.kind !== 'read' || request.name !== search.name) return http(request, signal);
// Your own request and parser: each part is the whole result so far.
for await (const part of searchStream(request.input, signal)) {
if (part.done) return { ok: true, value: part.value };
preview?.(part.value);
}
// The stream ended without its final part.
throw new Error('The search was interrupted');
};- Send the whole result so far with each preview. The store checks it
against the read's
outputschema and skips it if validation fails. - Only the final reply goes into the cache. Previews stay out of persistent storage, the data a server render sends to the browser and the records that reads share through entities.
- If the stream fails before the final reply, the store drops the preview
and shows the error until you call
refresh(). - Once a read has a confirmed value, that value stays visible throughout a reload, even if the transport sends more previews.
- A view ignores previews from the transport.
If your component suspends with useRead(handle), the first preview is
enough to replace its fallback. To show readers which results are still
provisional, pass { suspend: false } and check the snapshot's preview
field.
Stop a load nobody is waiting for
By default the store finishes a load even after the component that asked
for it unmounts. That gives the next reader a cached value. For a search
that follows each keystroke, though, there's little reason to finish
loading results for text the user has already changed. Set cancel: true
to have the store abort the transport's signal when the last fetching
subscriber leaves or pauses.
export const search = read({
name: 'books.search',
input: z.object({ q: z.string(), after: z.string().optional() }),
output: z.object({ books: z.array(bookShape), next: z.string().nullable() }),
cancel: true,
});If the user changes the query from fern to moss and nobody else is
reading fern, the store stops that request and ignores anything it sends
later. Any results already confirmed for fern stay cached. A pending
prefetch() or refresh() keeps a load alive until it settles. When
tabs share a request, the store only cancels it once every
tab has stopped waiting for it.
How long values last
A value can be old enough to reload and still worth showing while you wait. Three contract options, all in milliseconds, let you decide how the store treats it.
freshtells the store how long it can serve the value without checking with the server. The default is0, so a component that mounts with a cached value shows it immediately and starts a reload in the background.keepstarts counting when the last component stops showing the value. After five minutes by default, the store drops it and the next reader has to load it again. A duration too long for a timer (2³¹ ms or more, roughly 25 days) keeps the value for the session, as doesInfinity.expiresets a hard age limit. Once a value reaches it, the store stops showing it even while it reloads. By default values never expire.
import { read } from 'octane/data';
import { z } from 'zod';
export const stats = read({
name: 'books.stats',
output: z.object({ total: z.number().int(), read: z.number().int() }),
fresh: 30_000, // Show it for 30 seconds without reloading.
keep: 600_000, // Keep it for 10 minutes after the last reader leaves.
tags: ['shelf'], // Writes that change the shelf mark it stale.
});In this example, the shelf tag groups the stats with other reads that
depend on the shelf. A write can mark the whole group stale, as we'll see
in Writing data. For finer control, compute tags from the
read's input. Here a change to one project can mark just that project's
reads stale.
export const project = read({
name: 'project',
input: z.string(),
output: Project,
tags: (id) => [`project:${id}`],
});The store computes the tags once for each distinct input, using the input
as passed to store.read. For a view, that includes offset and limit.
When the store saves a value, it saves those tags along with it so writes
can still find it after a restart.
Read outside a component
The hooks use the same store you can call directly from an event handler,
a route loader, a test or any other code. Calling store.read gives you
a read handle without making a request. Loading starts when something
subscribes with fetching enabled, prefetches the read or asks it to refresh.
import { createDataStore, serverTransport } from 'octane/data';
import { books } from './contracts.data.ts';
import { data } from './data.tsrx';
const store = createDataStore({ transport: serverTransport(data) });
// Start a load early, such as when the pointer hovers a link.
await store.prefetch(books, undefined);
const handle = store.read(books, undefined);
const stop = handle.subscribe(() => {
const snapshot = handle.getSnapshot();
if (snapshot.status === 'ready') console.log(`${snapshot.value!.length} books`);
});
await handle.refresh(); // Reload now, keeping the current value on screen.
stop(); // The last subscriber leaving starts the `keep` timer.getSnapshot()gives you the current snapshot. It returns the same object until something changes, so you can use it directly withuseSyncExternalStore.subscribe(notify)starts observing the read and returns a function you can call to stop. To pause fetching for this subscriber, usesubscribe(notify, { fetch: false }). Stop and subscribe again withfetch: trueor omit the option to resume.refresh()starts a reload now and resolves when it settles.
Suppose you prefetch a page's data when someone hovers over its link.
When they click, the first reader can use that value even if it's already
older than fresh. The store only considers reloading a value because
of its age after a reader has shown it. Until then, a second prefetch
can reuse it too. The same rule applies to values from a server render's
seed, so a route can prefetch those values during hydration without
making a request.
You can also work with the cache directly through the store.
store.invalidate(tags)marks reads stale if they have a matching tag or hold one of the specified entities. The ones on screen reload.store.publish(read, input, value)lets you supply a value you obtained elsewhere. The store treats it just like the result of a load.store.forget(read, input)removes one cached value from memory and persistent storage.
Load a screen in one round trip
When each component loads its data on mount, the nesting of your components
can determine how long the screen takes to load. If a child sits inside an
@try block waiting for a project, its request for the project's tasks
starts only after the project arrives. On a slow connection, the user
waits for two round trips.
If the route already has the project ID, it can start all the reads that use that ID before rendering the screen. The components read as usual, and each part of the screen keeps its own cache entry and can load or fail independently.
// The route, before it renders the project screen.
store.prefetch(project, id);
store.prefetch(members, id);
store.prefetch(tasks, id);
store.prefetch(activity, id);Now suppose the screen also needs the project's owner. The browser learns
project.ownerId from the first reply, so it would still need a second
round trip to fetch the owner. You can move that lookup onto the server's
own network by giving the screen one read whose handler gathers all the
data it needs.
export const dashboard = read({
name: 'dashboard',
input: ProjectId,
output: Dashboard,
// The records it carries are shared with every other read of them.
entities: (value) => [
Project.from(value.project),
User.from([value.owner, ...value.members]),
Task.from(value.tasks),
],
});With one request the whole screen appears together. That means waiting for the slowest lookup, and a failure in any lookup fails the read. Keep a separate read for a part that might be slow or that another screen uses on its own.
On a server-rendered page, the route's prefetches can reuse the values
from the server render without making any requests. The
data-fetch-waves benchmark
measures how long the same screen takes to load with each of these
three approaches.
Writing data
A write contract describes a change you'd like the server to make.
Call store.write(contract, input) to request the change and get a
promise for the reply. In a component, get the store with useDataStore()
and call store.write just as you would anywhere else.
import { write } from 'octane/data';
import { z } from 'zod';
export const renameShelf = write({
name: 'shelf.rename',
input: z.object({ name: z.string().min(1) }),
output: z.object({ name: z.string() }),
invalidates: ['shelf'],
});The simplest way to keep the shelf up to date after a rename is to tell
the store which reads it affects. Here, once the server confirms the new
name, the store marks every read tagged shelf as stale and reloads the
ones on screen.
You can also compute invalidates from the write's validated input. For
a project rename, use the project's ID to reach just the reads
tagged for that project.
export const renameProject = write({
name: 'project.rename',
input: z.object({ id: z.string(), name: z.string().min(1) }),
invalidates: ({ id }) => [`project:${id}`],
});The store computes those tags twice. When it sends the write, it asks the server to include fresh values for the matching reads on screen in the reply. When the write settles, it computes the tags again.
Entities: one record, many reads
Reloading gets you the right data, but a slow reload can leave the user
waiting or make the page flicker. When someone changes a book's read
flag, you already know which field changed and which book it belongs to.
An entity gives the store a way to recognize that book wherever it
appears, so the list and the book's detail page can show the edit together.
import { entity, read, write } from 'octane/data';
import { z } from 'zod';
const bookShape = z.object({ id: z.string(), title: z.string(), read: z.boolean() });
/** Every read that holds a book shares its fields. */
export const Book = entity('book', bookShape);
export const books = read({
name: 'books.list',
output: Book.list, // A list of books: the store knows they are books.
});
export const book = read({
name: 'books.get',
input: z.object({ id: z.string() }),
output: Book.one, // One book.
});
export const setRead = write({
name: 'books.setRead',
input: bookShape.pick({ id: true, read: true }),
output: Book.one, // The reply is the saved book.
patches: Book, // The input is a partial book, keyed by its `id`.
});entity(name, schema, key?) gives the record type a name and tells the
store how to identify each record. It looks for the ID in id by default.
Pass a different key if yours lives elsewhere. Use Book.list for an
array of books and Book.one for a single book. Both validate each book
against the entity's schema and tell the store how to use it.
- A read with
Book.listorBook.oneas itsoutputshares the books it returns with every other read that holds them. - A write to
BookwithBook.oneas itsoutputtells the store that the reply is the saved book.
A shelf page might return the shelf's owner and a count along with the
books. Use entities to pick out the records the store should share.
Book.from(...) accepts a single book or an array, and you can select
records of several types in the same read.
export const shelfPage = read({
name: 'shelf.page',
output: z.object({ owner: userShape, books: z.array(bookShape), total: z.number() }),
entities: (page) => [User.from(page.owner), Book.from(page.books)],
});Using plain bookShape as the output checks the shape of the result.
Without an entity selection, the store treats it as a separate value,
so edits to a book elsewhere won't show up in that read.
On the write contract, describe what should happen to the shared record.
patches: Bookfinds the book by ID and merges the fields from the write's input into it.creates: Bookadds a book. While you're waiting for the reply, the store shows a draft made from the input and the new ID. You can supplydraft(input, id)to build that record yourself.removes: Booktells the store to remove the book with the given ID wherever it appears. The rules below describe how each read handles the deletion.
If the reply includes other data alongside the saved book, use record
to pick it out. For example, record: (reply) => reply.book gives the
store the server's version of the book without having to fetch it again.
How shared records behave
- Select complete records. Each read that selects
Bookmust return whole books that pass the entity's schema. When a newer copy arrives, it replaces the entire record. If a menu loads just the titles, give those rows their own entity or leave them out of the entity selection. - The start of the load determines which copy is newer. A reply can replace a record only if its load started later. A slow request that finishes last can't overwrite the result of a more recent request.
- Pending edits stay visible. The store keeps the server's copy as the confirmed value and applies your pending edits over it in every copy until the writes settle.
- A refusal rolls back the edit everywhere. If the server refuses a write, the store removes that edit from every copy in the same update.
- Deletion depends on the shape of the read. Lists and views drop a deleted book right away. A read whose entire value is one book keeps showing it until the read reloads, because its schema has no value for a missing book.
- Edits and feed events reach every read that selects the record. After the server confirms a write, views use the saved record from the reply. Other reads showing that record reload. All views share one copy of a given record, so a read that loads a newer copy updates any views that hold it. When an ordinary read reloads, other ordinary reads keep their own copies of the record.
- Sharing stops at the store boundary. Give each signed-in account its own store and retire it when that account signs out.
Optimistic edits and rollback
Declaring a write's effect makes the edit optimistic. When someone ticks a book's checkbox, the store applies the edit before it even sends the request. Once the server confirms the write, the store uses the values from the reply. If the server refuses it, the store undoes the edit in every read that showed it.
- 1. store.write(setRead, { id, read: true })
- 2. Apply the edit to every read holding the book; re-render now
- 3. Send the write, once, with an operation ID
- 4. Validate input, run the handler
- 5. Confirmed: reply with the saved book and refreshed reads
- 6. Show the server’s values; the promise resolves
- 7. Or refused: DataError with a code
- 8. Remove the edit everywhere; the promise rejects
The checkbox below gets its checked state from book.read throughout.
The store updates that field while the write is pending, so the component
can show the edit without keeping a local copy or tracking a separate
saving state.
import { useDataStore, useRead } from 'octane/data/octane';
import { books, setRead } from './contracts.data.ts';
export function BookList() @{
const store = useDataStore();
const list = useRead(store.read(books));
<ul>
@for (const book of list; key book.id) {
<li>
<label>
<input
type="checkbox"
checked={book.read}
onChange={() =>
void store.write(setRead, { id: book.id, read: !book.read }).catch(() => {})
}
/>
{book.title as string}
</label>
</li>
}
</ul>
}Octane uses native browser events. Toggling a checkbox fires change
immediately, so onChange works here. In a text field, use onInput
to respond to each keystroke. Differences from React
covers the event behavior in more detail.
In React, the checkbox calls the same write from its change handler.
/** @jsxImportSource react */
import { useDataStore, useRead } from 'octane/data/react';
import { books, setRead } from './contracts.data.ts';
export function BookList() {
const store = useDataStore();
const list = useRead(store.read(books));
return (
<ul>
{list.map((book) => (
<li key={book.id}>
<label>
<input
type="checkbox"
checked={book.read}
onChange={() =>
void store.write(setRead, { id: book.id, read: !book.read }).catch(() => {})
}
/>
{book.title}
</label>
</li>
))}
</ul>
);
}A reader can keep editing while earlier requests are still in flight. Here's what happens when those changes overlap.
- If a newer value arrives while an edit is pending, the store applies the edit again over the new value. Each edit sets specific fields, inserts a record by ID or deletes a record by ID. If the value already includes the edit, applying it again leaves the same result.
- When a reply contains several values, the store updates all of them before any component re-renders. Each render sees the whole server transaction.
- If you create a book and immediately rename it, the store waits for the server to confirm the new book before sending the rename. If the server refuses to create it, the store rejects the rename without sending it.
Your database may assign IDs to new records, for example with an
auto-incrementing key. Add serverId: (reply) => reply.id to the write
that creates the book. The store shows the new book under a temporary
ID until the reply arrives, then uses the server's ID for later writes.
When the server says no
Suppose the shelf already contains the book someone is trying to add.
The handler can refuse the write by throwing a DataError with a short
code such as 'duplicate'. The browser receives that code and any data
you attach exactly as the handler sent them.
import { DataError } from 'octane/data';
import { createDataHandler } from 'octane/data/server';
import { addBook, type Book } from './contracts.data.ts';
const shelf: Book[] = [];
export const handler = createDataHandler({}, (handle) => [
handle(addBook, (input, { operationId }) => {
if (shelf.some((book) => book.title === input.title)) throw new DataError('duplicate');
const book = { id: operationId, title: input.title, read: false };
shelf.push(book);
return book;
}),
]);By the time the write's promise rejects with the DataError in the
browser, the store has already undone the edit. You can use the code
to explain what happened. A schema check that fails also produces a
DataError, with the code 'invalid' and the validator's messages in
issues.
import { DataError } from 'octane/data';
import { addBook } from './contracts.data.ts';
import { store } from './store.ts';
try {
await store.write(addBook, { title: 'Kindred' });
} catch (error) {
if (error instanceof DataError && error.code === 'duplicate') {
console.log('That book is already on the shelf');
}
}When the reply is lost
The connection can drop just after the server saves a book, before its
reply reaches the browser. Retrying might add the book twice, and
rolling back might hide a book the server saved. The store leaves the
edit on screen and rejects the write's promise with a
DataUncertainError. It waits for you to find out what happened before
it does anything else with that edit.
Each write has an operation ID, available to the handler as
call.operationId. If your handler records the IDs of the writes it
applies, you can ask the server about a particular write with a
receipt read. Once you have the answer, call store.settle to keep
the edit or roll it back.
// contracts.data.ts
export const receipt = read({
name: 'books.receipt',
input: z.object({ operationId: z.string() }),
output: z.object({ applied: z.boolean() }),
});import { DataUncertainError } from 'octane/data';
import { receipt, setRead } from './contracts.data.ts';
import { store } from './store.ts';
export async function markRead(id: string) {
try {
await store.write(setRead, { id, read: true });
} catch (error) {
if (!(error instanceof DataUncertainError)) throw error;
// Ask the server, then keep the edit or roll it back. Nothing is resent.
const handle = store.read(receipt, { operationId: error.operationId });
await handle.refresh();
const snapshot = handle.getSnapshot();
if (snapshot.status === 'ready') store.settle(error.operationId, snapshot.value!.applied);
}
}Your handler can also check the recorded IDs before applying a write. That makes it safe to call the handler twice with the same operation ID. With persistence, the store can look up the receipt for you, even if the page has reloaded.
Views and pagination
Imagine the shelf has two lists, "Unread" and "Finished", both sorted by title. When someone marks a book as read, it should move straight from one list into its place in the other. With plain reads you could ask the server to send both lists again, though the browser already has enough information to work out where the book belongs.
A view gives the store that information. You choose an entity, use
where to say which records belong in the list and order to say how
to sort them. The store applies those rules to the records it holds.
Editing a book can move it within a list, add it to another or remove
it from one, all in the same update.
import { entity, view } from 'octane/data';
import { z } from 'zod';
const bookShape = z.object({ id: z.string(), title: z.string(), read: z.boolean() });
export const Book = entity('book', bookShape);
export const unread = view({
name: 'books.unread',
of: Book,
where: (book) => !book.read,
order: [['title', 'asc']],
limit: 50, // Rows shown when no window is asked for.
});
export const finished = view({
name: 'books.finished',
of: Book,
where: (book) => book.read,
order: [['title', 'asc']],
limit: 50,
});List the keys in order from most to least significant. If two books
have the same title here, the store uses the entity's key to break the
tie. You can set max to limit how many rows a request can ask for.
The default is 500.
Each request asks the server for a window of the view, up to limit
records starting at offset. The handler needs to filter and sort the
books exactly as the store does before it takes this slice. It can use
the functions on the view contract itself.
import { createDataHandler } from 'octane/data/server';
import { unread, type Book } from './contracts.data.ts';
const shelf: Book[] = [];
export const handler = createDataHandler({}, (handle) => [
handle(unread, (input) =>
shelf
.filter((book) => unread.view.where(book, input))
.sort(unread.view.compare)
.slice(input.offset, input.offset + input.limit),
),
]);If you keep the books in a database, use the corresponding WHERE and
ORDER BY in your query. The store asks for a few more rows than it
shows. If a book moves up into the visible window from just below it,
the store can show it without another request.
Pay particular attention to how your database sorts. For the windows
to line up, its ordering has to match the view's compare function
exactly.
- Include every key in
orderwith its specified direction, followed by the entity's key to break ties. For the shelf, that'sORDER BY title, id. comparefollows JavaScript's<operator, which sorts numbers and dates by value and strings by character code. For strings, use a binary collation like SQLite's default. In PostgreSQL, the default usually follows the rules of a language, so specifyCOLLATE "C". Binary collation and<differ when you compare a character outside the Basic Multilingual Plane, such as an emoji, with a character in the range U+E000 to U+FFFF.nullsorts before every other value. SpecifyNULLS FIRSTif your database would put it last.
If the two sides disagree, a book can end up in the wrong position or
go missing where one page ends and the next begins. To catch this, the
handler checks the order before it replies, and the store checks every
window it loads. If rows arrive out of order, the read fails with
invalid and names the view.
When only the server can order a list
Sometimes the order depends on something only the server knows, like
a database's language-specific collation, a relevance score or a ranking
based on data the browser never sees. Let the server decide which rows
belong and where to put them. Use a plain read that returns the records
in order, selects them with Book.list or entities, and
loads successive pages with a cursor.
While a write is pending, the store can still show the edit.
- An edited record updates immediately in its current position.
- A new record appears once, after the rows loaded so far.
- A deleted record disappears immediately.
- When the server confirms the write, the list reloads from the first page in the server's order.
You can see both approaches in
data-database.test.ts,
which uses SQLite to serve a view and a read with cursor pages.
In a component, you use a view like any other read.
useRead(store.read(unread)) gives you its default window. To ask for
a particular window, pass { offset, limit } to store.read along
with any parameters declared by the view's input schema.
Join records from other entities
A list of messages usually shows who wrote each one, just as a list of
tasks might show who's assigned to each task. If you join messages to
authors in the component, you need a second read and a lookup for each
message on every render. Rebuilding the list this way also gives you a
new object for every row when anything changes. You can have the store
do the join by declaring the relation with with on the view.
import { entity, view } from 'octane/data';
import { z } from 'zod';
export const User = entity('user', z.object({ id: z.string(), name: z.string() }));
export const Message = entity(
'message',
z.object({ id: z.string(), authorId: z.string().nullable(), text: z.string(), sent: z.date() }),
);
export const inbox = view({
name: 'messages.inbox',
of: Message,
// Under `author`, the user whose ID is in `authorId`.
with: { author: [User, 'authorId'] },
order: [['sent', 'desc']],
});A row in inbox now includes the message and an author of type
User | undefined. If authorId is empty or the user doesn't exist,
the row has no author. Have your handler return the related records
under the names you chose in with, as you would with a database join.
It can omit a missing record or send null.
handle(inbox, async (input) => {
const rows = await db.messages.page(input.offset, input.limit);
const authors = await db.users.byIds(rows.map((row) => row.authorId));
return rows.map((row) => ({ ...row, author: authors.get(row.authorId) }));
});The store treats the authors as shared User records, just as it
would if you'd loaded them in a view of users. This matters when
someone edits a user or changes the author of a message.
- If someone edits an author's name, every message by that author and every other read of the user shows the new name together, before the server replies.
- The store reuses a row object until its message or author changes, so a memoized row component only needs to re-render when its own row changes.
- Within the message views, a change to an author reaches only those that have a message by that author.
- An edit or a feed event can point a message at a different author. If the store already has that user, perhaps because they're in a user picker, the author appears immediately. Otherwise the author is absent until the store has the record. The view fetches it once the edit is confirmed.
A relation can point to a single record, and where and order only
see the view's own record. If you need to join a list of related
records or to filter or sort messages by a field on the author, shape
the result on the server with a plain read and mark its
entities.
Load a page at a time
For a list that grows as you scroll or press "Show more", create a
pages handle with pages(store, view, params?). Pass it to
usePages to render the pages loaded so far as a single list. The
hook returns without suspending, so the component can show the books
it already has while the next page loads.
import { pages } from 'octane/data';
import { useDataStore, usePages } from 'octane/data/octane';
import { unread } from './contracts.data.ts';
export function UpNext() @{
const list = usePages(pages(useDataStore(), unread));
<section>
<ul>
@for (const book of list.value ?? []; key book.id) {
<li>{book.title as string}</li>
}
</ul>
@if (list.more) {
<button type="button" disabled={list.loadingMore} onClick={() => void list.loadMore()}>
Show more
</button>
}
</section>
}Each page is a window of the view. Its records are shared with the
other pages and with other views, so an edit can move a book across
a page boundary just as easily as it can move it within a page.
Outside a component, call pages(store, view, params?, size?) to
get a handle for the combined list. It offers getSnapshot,
subscribe, loadMore and refresh.
Pages from a cursor
For a list the server orders, such as search results, each page may
come with a cursor telling you where the next one starts. Define
the page as an ordinary read. Then give pages a function to pull
the rows out of a page and another to turn its cursor into the input
for the next request.
import { pages } from 'octane/data';
import { useDataStore, usePages } from 'octane/data/octane';
import { search } from './contracts.data.ts';
const byCursor = {
rows: (page: { books: Book[] }) => page.books,
next: (page: { next: string | null }, input: { q: string; after?: string }) =>
page.next ? { ...input, after: page.next } : null,
};
export function Results(props: { q: string }) @{
const list = usePages(pages(useDataStore(), search, { q: props.q }, byCursor));
<section>
<ul>
@for (const book of list.value ?? []; key book.id) {
<li>{book.title as string}</li>
}
</ul>
@if (list.more) {
<button type="button" disabled={list.loadingMore} onClick={() => void list.loadMore()}>
Show more
</button>
}
</section>
}- Return
nullorundefinedfromnextwhen you've reached the last page. The list also stops if it gets a cursor it has already followed. An empty page with a new cursor still has more to load. - Calling
loadMore()while the next page is loading joins the request already in progress. If it fails, the existing rows stay visible and the nextloadMore()retries the same cursor. - If the next page sends previews, its provisional
rows appear in the list with
list.previewset totrue. list.valuekeeps the same array until a row changes. A component that depends only on the rows can skip updates toloadingMoreorrefreshing.refresh()starts again at the first page, following the cursors the server now returns. The current rows stay on screen until all the replacement pages are confirmed, then the store swaps them in together. It does the same when a write marks the pages stale and the first page comes back with a different cursor.
Forms that work before JavaScript
With octane/data, a reader can submit a form to add a book as soon
as the browser shows the page. Before hydration, or with JavaScript
turned off, the browser sends a native POST and the server runs
the write. After hydration, the same form submits through the store,
which can show the optimistic edit while the write is pending.
On the write contract, use form to declare which fields the browser
will submit and how to read each one. Here the reader just needs to
supply the title.
import { entity, write } from 'octane/data';
import { z } from 'zod';
const bookShape = z.object({
id: z.string(),
title: z.string().trim().min(1, 'Enter a title'),
read: z.boolean(),
});
export const Book = entity('book', bookShape);
export const addBook = write({
name: 'books.add',
input: bookShape.pick({ title: true }),
output: bookShape,
creates: Book,
record: (book) => book,
form: { title: 'text' },
});The handler refuses any fields the write hasn't declared. For each field, choose the type that matches what the form sends.
- Use
'text'for ordinary text or'number'for a number. - Use
'secret'for text such as a password. If the submission is refused, the server leaves that field out of the values it sends back to the page. - Use
'boolean'for a field that sends exactly"true"or"false", as a hidden input would. - Use
'checkbox'when the presence of the field meanstrueand its absence meansfalse.
In the component, useForm gives you the attributes and hidden
fields for the <form>, along with the state of the submission.
import { useForm } from 'octane/data/octane';
import { addBook } from './contracts.data.ts';
export function AddBook() @{
const add = useForm(addBook);
const message = add.issues.title ?? (add.error ? 'Could not add that book' : '');
<form {...add.attrs}>
{add.hidden()}
<input name="title" aria-label="Book title" defaultValue={add.values.title ?? ''} />
<button type="submit" disabled={add.pending}>
Add
</button>
@if (message) {
<p role="alert">{message as string}</p>
}
</form>
}- Spread
attrson the<form>. It suppliesmethod="post"for the browser and anonSubmithandler that takes over after hydration. - Render
hidden(values?)inside the form to identify the write and the form itself. You can also pass values the reader won't type, such as the ID of a row. - Use
pending,values,issuesanderrorto show the state of the latest submission. After a refusal,valueslets you fill the fields back in andissuesgives you the first message for each field. A message about the whole input uses the key''. - If you need to run code before or after submitting, call
submit(eventOrFormData)yourself to send the write through the store.
If each row has its own form, pass a key to useForm. With
useForm(removeBook, book.id), the pending state and any messages
belong to the book the reader tried to remove.
On the server, call handler.forms before you render the page. It
recognizes a native form POST and runs the write. On success, the
browser gets a 303 redirect back to the page. If the server refuses
the write, render the page again. The store's seed carries
the submitted values and messages back to the browser.
// server.ts
import { createDataHandler } from 'octane/data/server';
import { addBook } from './contracts.data.ts';
import { addToShelf } from './db.ts';
export const handler = createDataHandler(
{
context: (request) => ({ account: request.headers.get('x-account') ?? 'guest' }),
// Signs each page's forms. Keep it in server-only configuration.
secret: process.env.FORM_SECRET!,
// The account a request acts for: a form signed for one account is refused for another.
grant: (context) => context.account,
},
(handle) => [handle(addBook, (input, { account }) => addToShelf(account, input.title))],
);// page.ts — the server route that renders a page and accepts its form posts.
import { handler } from './server.ts';
import { renderPage } from './render.ts';
export async function page(request: Request): Promise<Response> {
const forms = await handler.forms(request);
if (forms.response) return forms.response; // An accepted POST: redirect back.
const html = await renderPage(request, forms.form);
return new Response(html, { status: forms.status, headers: { 'content-type': 'text/html' } });
}Pass forms.form to the page's store with
createDataStore({ transport, form }), as shown in
server rendering. The server signs the page's forms for the
account and assigns fresh operation IDs on each render. If someone
submits the same form twice from that page, the write is applied once.
Serve your contracts
The shelf needs two handlers here, one to list the books and one to mark a
book as read. In createDataHandler(options, define), the options tell Octane
how to authenticate the request and find the shelf. Your define callback
pairs each contract with its function using handle and returns the list of
handlers. Each name can appear only once. The callback also receives
defineHandler for serving all the contracts in a module
together.
import { DataError } from 'octane/data';
import { createDataHandler } from 'octane/data/server';
import { books, setRead } from './contracts.data.ts';
import { accountFrom, shelfFor } from './accounts.ts';
export const handler = createDataHandler(
{
// Runs for every request: authenticate it and return what handlers need.
context: (request) => {
const account = accountFrom(request);
if (!account) throw new DataError('unauthorized');
return { account, shelf: shelfFor(account) };
},
// Other origins that may call this endpoint. The request's own is always allowed.
allowedOrigins: ['https://admin.example.com'],
},
(handle) => [
handle(books, (_, { shelf }) => shelf),
handle(setRead, (input, { shelf }) => {
const book = shelf.find((item) => item.id === input.id);
if (!book) throw new DataError('missing');
book.read = input.read;
return book;
}),
],
);By the time either function runs, Octane has validated its input. The second
argument, call, includes everything you returned from context. That's
where { shelf } comes from in both handlers. You can also use these fields
on call.
call.requestis the incomingRequest.call.signalaborts if the client disconnects.call.operationIdis the ID the client assigned to the write. It's empty for a read.call.read(contract, input)runs another read in the same process, with the same context.
If the request came through a server function or framework middleware, your
middleware may already have authenticated the user. You can get that viewer
from caller, the second argument to context.
Serve a whole module
As the shelf grows, it's handy to see all its server functions together.
Import the contracts as a namespace and pass it to defineHandler along with
an object whose keys match the module's exports. Here the shelf also has a
stats read.
import { createDataHandler } from 'octane/data/server';
import * as Shelf from './contracts.data.ts';
export const handler = createDataHandler({ context }, (_, defineHandler) =>
defineHandler(Shelf, {
books: (input, { shelf }) => shelf.slice(input.offset, input.offset + input.limit),
stats: (_, { shelf }) => ({ total: shelf.length }),
setRead: (input, { shelf }) => markRead(shelf, input.id, input.read),
}),
);Each function gets the same types it would get from handle. The contract and
your context determine the types of input, call and the result.
TypeScript expects a function for each exported read, view, write and feed. If
you add a contract to Shelf, you'll get a compile error here until you give
it a function. A typo or an extra key is also an error. You can leave
entities, schemas and other exports out of the object.
defineHandler returns a list of ordinary handlers. If you also serve a
contract from another module, you can combine the two styles in one list with
[...defineHandler(Shelf, { … }), handle(other, run)].
If several contracts share an implementation, write a small factory and call
it for each key. The contract check needs to see where you
use the contract, so pass the factory just the part it needs. For example,
books: windowOf(Shelf.books.view) lets the build see the reference to
Shelf.books even though windowOf does the work. If you need to name the
function's type, Implementation<C, T> means “serves contract T with
context C.”
Declare a contract with its function
You can also keep the server function next to its contract in the *.data.ts
file. A read, view, write or feed takes the function as its second argument.
For example, here you can read the schema for adding a book and the database
call that saves it side by side.
// books.data.ts
import { entity, read, write } from 'octane/data';
import type { DataCall } from 'octane/data/server';
import { z } from 'zod';
import { db } from './db.server.ts';
export const Book = entity('book', z.object({ id: z.string(), title: z.string() }));
/** What these functions need from the handler's `context`. */
type Call = DataCall & { account: string };
export const book = read(
{ name: 'books.one', input: z.string(), output: Book.one },
(id, { account }: Call) => db.book(account, id),
);
export const addBook = write(
{ name: 'books.add', input: z.object({ title: z.string() }), output: Book.one, creates: Book },
(input, { account, operationId }: Call) => db.addBook(account, operationId, input.title),
);// data.server.ts
import { createDataHandler } from 'octane/data/server';
import * as Books from './books.data.ts';
export const handler = createDataHandler({ context }, (_, defineHandler) => defineHandler(Books));Both contracts already have a function, so defineHandler(Books) has
everything it needs. If only some contracts have functions, pass an object
with keys for exactly the ones that still need them. In the example, the
Call annotation says the functions need an account. TypeScript checks that
the handler's context supplies it when you pass Books to defineHandler.
The server identifies each request by its stable contract name, checks the input against its schema before calling your function, and checks the result before sending it back. Your function decides what the caller is allowed to do.
Notice the import of db.server.ts in the same file the browser imports. The
Octane Vite and Rspack plugins strip the server functions from the browser
build, along with imports and module-level constants used only by those
functions. That's how the database code stays on the server. If your build
uses neither plugin, put the functions in the object you pass to
defineHandler.
Serve through a server function
In an Octane app, start with the setup from your first read.
The store uses serverTransport(fn) to send a request through a
module server function, where handler.serve(request, call) answers it. You
get your app's existing origin checks and middleware. During a server render,
the store can make that same call in process and skip the network trip.
Serve over HTTP
If you already have an HTTP server, you can mount the handler on a route. Its
signature is (request: Request) => Promise<Response>. It works anywhere you
can use a fetch-style handler that takes a Request and returns a
Response, including Bun, Deno, Workers, Node with an adapter, and framework
routes.
// A route in any Request/Response server.
import { handler } from './server.ts';
export function POST(request: Request): Promise<Response> {
return handler(request);
}If you mounted that route at /api/data, give httpTransport the same URL
when you create the browser store.
import { createDataStore, httpTransport } from 'octane/data';
export const store = createDataStore({
transport: httpTransport('/api/data', { headers: { 'x-app-version': '1' } }),
});Both transports use devalue to encode requests, so dates, maps and sets survive the trip. If the transport can't decode a response as a reply, the store treats the reply as lost. Say a proxy returns an error page after you mark a book as read. The server might already have saved the change, so the store needs a definitive refusal before it can roll the edit back.
To write your own transport, implement
(request, signal, preview?) => Promise<DataReply>. Resolve the promise with
a reply when you know the outcome, and reject it when the outcome is unknown.
For a read, you can call preview with partial results while the promise is
pending, as in Show results as they arrive.
Let the build check your contracts
It's easy to wire a button to a write and forget to add the server handler. A
contract is a plain value, so you might only find out when someone clicks the
button. The Octane Vite and Rspack plugins can catch this during the build. To
enable the check, declare all your contracts in *.data.ts or *.data.js
modules and import octane/data/manifest somewhere in your app.
The plugin needs to be able to follow a contract from its declaration to each place you use it. There are four rules that make this possible. Each has its own build error code.
-
Export each contract as a
constand give it a literal name. The plugin reads the declaration from source, so the name has to be there before any code runs.// books.data.ts export const setRead = write({ name: 'books.setRead', input: SetRead }); // ✓ export const shelfBooks = (shelf: string) => read({ name: `books.${shelf}`, input: Shelf }); // ✗ built at runtime -
Keep the contract module to imports, types and
constdeclarations. Both the server and the browser import it. Keep server-only dependencies out of the shared code and avoid running code when the module loads. Even a top-levelconsole.log('loaded')inbooks.data.tsis an error. -
Name the contract directly wherever you use it. For
store.read,prefetch,publish,forget,write,form,useForm,handleanddefineHandler, the plugin looks at the first argument. Forpagesandlisten, it looks at the second. It also follows contracts in the propertiesof,creates,patches,removes,put,remove,read,feeds,writesandreceipt.store.write(done ? setRead : setUnread, input); // ✗ chosen at runtime store.write(Shelf[name], input); // ✗ chosen by key, from import * as Shelf store.write(Shelf.setRead, input); // ✓Here you can use
setReadfor both actions and pass the desired state in its input. -
Keep the contract where the plugin can follow it. Once you pass a contract to your own helper or put it in an arbitrary variable or list, the plugin loses track of it. If a helper needs to submit a write, give it a callback that calls
store.writewith the contract.submit(session, setRead, input); // ✗ `submit` receives a contract submit(session, (store) => store.write(setRead, input)); // ✓
If you need to do the same thing for several contracts, you can use .map or
for…of over an inline list. The plugin can see that list below can only be
books or unread. Inside the loop, you can use list anywhere the plugin
expects a contract or read a property from it. Those are the only uses the
check allows.
export const handlers = [books, unread].map((list) => handle(list, serveList));
for (const list of [books, unread]) store.prefetch(list);Once the plugin can trace the contracts, it can tell you where the client and server disagree. It checks the following on every build.
- Each read, view, write or feed the app uses needs exactly one handler from
createDataHandler. The plugin reports both missing and duplicate handlers. - Each contract needs a unique name.
- If the plugin finds a contract the app never uses, it reports a hint.
Even the client build can find a missing server handler. The plugin reads the
whole project for the check and leaves the server handlers out of the client
bundle. You'll see errors as warnings on the dev server and as failures in a
production build. You can also run the check with octane analyze.
To enable the check without importing the manifest, set data: true on the
plugin. Set data: false to disable both the manifest and the check.
Strong compiler checks lists the
individual diagnostics.
The generated manifest
The plugin uses the same *.data.ts modules to generate
octane/data/manifest. The manifest has three exports.
| Export | What it is for |
|---|---|
contracts | Every read, view, write and feed, in name order: what createReplica needs. |
writes | The writes among them, for a journal that keeps every write. |
identity | What createReplica compares to tell this build's contracts from another deploy's, as a string. |
The dev server updates the manifest as you add or remove contract modules. You need the plugin to generate it. Importing the manifest without the plugin throws.
Consider the session in the shelf example. The shared owner needs to know about all the contracts, and the journal needs the writes. If you keep those lists by hand, adding a write means remembering to update both.
// Before: every new contract had to be added here too.
const contracts = [
books,
finished,
unread,
stats,
receipt,
addBook,
setRead,
removeBook,
shelfChanges,
];
const persist = {
storage,
partition,
key,
journal: { writes: [addBook, setRead, removeBook], receipt },
};
createReplica(sharedOwner(partition), { transport, persist, contracts });The hand-written contracts list also runs into rule 4. The plugin doesn't
recognize the contracts option of createReplica as a place to name
individual contracts, so it can't trace them through the list. Import both
lists from the manifest and the next write you declare will appear in both
automatically.
// After
import { contracts, writes } from 'octane/data/manifest';
import { receipt } from './contracts.data.ts';
const persist = { storage, partition, key, journal: { writes, receipt } };
createReplica(sharedOwner(partition), { transport, persist, contracts });Server rendering and hydration
By the time the server has rendered the shelf, it's already loaded the books. You can give the browser those same values so it can hydrate the list without fetching it again. The server store produces a seed, a JSON snapshot of its values that travels with the HTML.
- Request storecreateDataStore, one per request
- HTMLevery useRead resolved
- Seed<script type="application/json">
- Browser storeadopts values on first read
- Hydrated pageno requests
Create a store for each page request so its transport calls the handler in
process under that request's account. Once the render finishes, call
dehydrate() to take the snapshot. The finally block calls retire() when
the request is over.
// render.ts — runs on the server for each page request.
import { createDataStore, serverTransport } from 'octane/data';
import { prerender } from 'octane/static';
import { App } from './App.tsrx';
import { data } from './data.tsrx';
export async function renderPage(template: string): Promise<string> {
const store = createDataStore({ transport: serverTransport(data) });
try {
const { html, css } = await prerender(App, { store });
const seed = store.dehydrate();
return template
.replace('<!--app-html-->', () => css + html)
.replace(
'<!--app-seed-->',
() => `<script type="application/json" id="data-seed">${seed}</script>`,
);
} finally {
store.retire(); // A request's store ends with its request.
}
}prerender from octane/static waits for every suspended read. By the time
it returns, the HTML is complete and you can call dehydrate(). The text it
produces is safe to embed in a <script type="application/json"> element. If
you serve your contracts over HTTP, use handler.transport(request) to get an
in-process transport for the incoming Request.
In the browser entry, pick up the seed from that script element and give it to
the store before calling hydrateRoot.
// main.ts — the browser entry.
import { hydrateRoot } from 'octane';
import { openDataStore } from 'octane/data/client';
import { App } from './App.tsrx';
import { session } from './session.ts';
const seed = document.getElementById('data-seed')?.textContent ?? null;
const store = openDataStore(session.account, { seed });
hydrateRoot(document.getElementById('root')!, App, { store });The store hydrates from its seed without waiting for the data worker. The first
time a component asks for a seeded value, the store can give it the server's
result immediately. The clock for fresh and expire starts when
the server loads the value and keeps running through hydration. If the HTML
spent time in a cache and you know how long, pass that duration in
milliseconds as seedAge.
An Octane page and a React page can share a server because the store handles
the seed format for both. In React, call prerender from react-dom/static,
then store.dehydrate(). Give the seed to the browser store before calling
hydrateRoot from react-dom/client.
Realtime feeds
Suppose you're looking at the shelf when someone adds a book. So far, your page would only find out the next time it asked the server. With a feed, the server can send the change as it happens. Every page listening can update its list straight away, without another load. The change might just as well come from a book you marked as read in another tab, or from a background job that just finished.
- Your eventsdatabase, queue, pub/sub
- Feed handlervalidates each event; cursor, gap
- serverListener
- webSocketListener
- pubSubListener
- Storefeed.changes → put, remove, read
- Every readholding those records
Describe the events
The shelf sends an event when a book changes or leaves the list. In the feed
contract, event describes the shape of those messages. The changes
function tells the store how to apply one. Here, adding or removing a book
also updates the counts in stats.
import { entity, feed, read } from 'octane/data';
import { z } from 'zod';
const bookShape = z.object({ id: z.string(), title: z.string(), read: z.boolean() });
export const Book = entity('book', bookShape);
const counts = z.object({ total: z.number().int(), read: z.number().int() });
export const stats = read({ name: 'books.stats', output: counts, tags: ['shelf'] });
const shelfEvent = z.discriminatedUnion('kind', [
z.object({ kind: z.literal('put'), book: bookShape, counts }),
z.object({ kind: z.literal('removed'), id: z.string(), counts }),
]);
export type ShelfEvent = z.infer<typeof shelfEvent>;
export const shelfChanges = feed({
name: 'books.changes',
event: shelfEvent,
changes: (event) => [
event.kind === 'put' ? { put: Book, value: event.book } : { remove: Book, id: event.id },
{ read: stats, value: event.counts },
],
// If events may have been missed, these reads reload.
covers: ['book', 'shelf'],
});A single event can describe several changes, as it does here. Each change takes one of four forms.
- Use
{ put: Entity, value }when the event includes the current record from the server. Every read and view that holds the record sees the new fields, and views adjust their order. - Use
{ remove: Entity, id }when the server deleted a record. The store removes it from every list. - Use
{ read: Read, input?, value }when the event includes the entire result of a read, such as the new count. - Use
{ invalidates: [...] }when the event tells you something changed but lacks the new value. Reads with those tags reload.
The store keeps track of which reads hold each record. When a book changes, it can go straight to the reads that need updating. Even if you have thousands of other reads loaded, they add no work to that event or to an optimistic edit.
covers tells the store which tags and entities rely on this feed. If the
connection drops or the server reports a gap, the store may have missed a
change to any of them. It marks the corresponding reads stale and reloads the
ones on screen.
Serve the events
On the server, write the feed handler as an async generator. While the
connection is open, the generator yields messages called frames. It stops
when call.signal aborts. The frame you yield depends on what you know about
the client's position.
{ event, id?, cursor? }delivers an event. Anidlets the store recognize and drop a duplicate. Acursortells it where to resume after this event.{ gap: true }tells the store it missed events. You might send it when the client's cursor is too old for your change log.{ cursor }on its own tells the store the connection is open and gives it a starting position.
import { createDataHandler } from 'octane/data/server';
import { shelfChanges } from './contracts.data.ts';
// Your app's change log: each change has a position and its event.
import { changesAfter, latestPosition, nextChange } from './changes.ts';
export const handler = createDataHandler({}, (handle) => [
handle(shelfChanges, async function* (_, { cursor, signal }) {
let seen = cursor === null ? latestPosition() : Number(cursor);
yield { cursor: String(seen) }; // Open, from here.
while (!signal.aborted) {
for (const { position, event } of changesAfter(seen)) {
seen = position;
yield { event, id: String(position), cursor: String(position) };
}
await nextChange(signal);
}
}),
]);On reconnect, call.cursor gives the handler the last position the client
saw. In the example, changesAfter(seen) picks up just after that position.
The server checks every event against the feed's schema before sending it.
Connect the store
Choose the store's listen option based on how your server delivers events.
The shelf can use a server function alongside the one it already uses for
reads and writes. If you have a WebSocket endpoint or a message broker, you
can use that too.
- With
serverListener(fn), amodule serverfunction returnshandler.listen(request, call)to stream the events. Each connection lasts up to 25 seconds to stay within the time limit for a server call. The store then reconnects from its cursor. webSocketListener(url)opens a WebSocket for each connection. On the server,handler.accept(socket, request, caller?)serves the socket without a time limit and refuses connections from other origins.pubSubListener(subscribe)uses the page's existing broker. If the broker keeps no history, there's no cursor to resume from. After a dropped subscription, the store reloads the reads the feed covers.
// data.tsrx
module server {
import type { ServerCallContext } from 'octane/server';
import { handler } from './server.ts';
export async function data(request: string, call: ServerCallContext) {
return handler.serve(request, call);
}
export function events(request: string, call: ServerCallContext) {
return handler.listen(request, call);
}
}
import { data, events } from 'server';
export { data, events };// store.ts
import { createDataStore, serverListener, serverTransport } from 'octane/data';
import { data, events } from './data.tsrx';
export const store = createDataStore({
transport: serverTransport(data),
listen: serverListener(events),
});In the browser, put the same listen in your data client.
The data worker holds the connections, one for every tab listening to a feed
with the same parameters, as in Sharing across tabs.
Listen while a component is mounted
A feed only needs a connection while it has listeners. The badge below uses
useFeed to listen for as long as it's mounted and show how the connection is
doing. The status is 'connecting' as the connection opens, 'live' once
it's open, and 'offline' while the store waits to retry. If another
component listens to the same feed, the two share a connection.
import { listen } from 'octane/data';
import { useDataStore, useFeed } from 'octane/data/octane';
import { shelfChanges } from './contracts.data.ts';
const LABELS = { connecting: 'Connecting…', live: 'Live', offline: 'Reconnecting…' };
export function LiveBadge() @{
const feed = useFeed(listen(useDataStore(), shelfChanges));
<p data-feed={feed.status}>{LABELS[feed.status] as string}</p>
}Outside a component, listen(store, feed, params?) gives you the same handle
with getSnapshot and subscribe. The first subscription opens the
connection and the last unsubscribe closes it. If the connection fails, the
store waits a little longer between attempts, varying the delay up to a
maximum of 30 seconds.
If your app already subscribes to events, you can pass a list of changes to
receive(store, changes). The store applies them just as it would for a feed
event. Validate the values against a schema first, since receive accepts
them as they are.
Feeds and server rendering
A book could be added after the server renders the shelf but before the browser connects to the feed. To make sure the browser hears about that book, include the page's feeds when you create the server store.
import { createDataStore, serverTransport } from 'octane/data';
import { shelfChanges } from './contracts.data.ts';
import { data } from './data.tsrx';
const store = createDataStore({
transport: serverTransport(data),
feeds: [shelfChanges],
});Before loading its first read, the store asks each feed for its current
position and includes that position in the seed. The browser resumes from
there, so it receives any changes made during the render or on the way to the
browser. For this to work, have your feed handler yield its position first
when call.cursor is null, as the shelf handler does above.
Persistence and offline
Normally, reloading the page means loading the shelf into an empty store. Set
persist to save confirmed values on the device between visits. The next time
the store starts, it can show the saved books straight away. Like a seed, each
saved value keeps its age. A fresh value saves a request, and a stale one
gives the reader something to look at while the store fetches an update.
import { autoBudget, createDataStore, indexedDBStorage, serverTransport } from 'octane/data';
import { data } from './data.tsrx';
import { session } from './session.ts';
export const store = createDataStore({
transport: serverTransport(data),
persist: {
storage: indexedDBStorage({ name: 'my-app' }),
// The account the store acts for; each account's values are kept apart.
partition: session.account,
// A random per-user secret from the signed-in session, never a password.
key: session.cacheKey,
// How much to keep, in characters of saved text. 'auto' sizes it by device.
budget: (device) => autoBudget(device),
},
});In this example, the session supplies both the account and its cache key, and
the device determines how much to keep. In the browser, put the same options
in your data client's persist, as a function of the
account, as in Sharing across tabs, so the data worker does the
encryption and the saving. A few details matter when you're
deciding what to save.
- Each account's cache is private. The store encrypts values with
keyand uses a keyed hash for every name it puts in storage. People sharing a browser can't read or list one another's values. Get the key from the signed-in session, for example from a per-user secret issued by your server at sign-in. You can use a string or bytes containing at least 128 random bits, or an HKDFCryptoKeywithderiveKeyusage. The key can be non-exportable. - Only confirmed values go into the cache. The store keeps pending edits out of the saved snapshot. If the server refuses an edit, it won't reappear from the cache on the next visit.
- The budget applies to saved values. After each save, the store drops
expired values first. When it needs to make room, it works through the least
recently used values until it's down to 90% of the budget, keeping anything
on screen.
autoBudgetallows 1 MB on small devices, 2 MB on devices with up to 4 GB of memory and 5 MB above that. It halves the budget when the user enables data saving and caps it at 1% of the storage quota. - The store checks the version before opening a saved value. If the shape
of the output schema or the read's
versionhas changed, the store discards the value unread.
For a read that holds a secret or anything else you want to keep off disk, set
persist: false on the read itself. If you change what a saved value means,
change the read's version so the store knows to discard the old one.
Use indexedDBStorage in a browser, or memoryStorage() for tests and hosts
where you want to keep everything in memory. If you're writing an adapter for
OPFS or native storage, the PersistentStorage interface has four methods to
implement (index, get, commit and clear). The adapter only ever sees
hashed names and encrypted text.
Writes that survive a reload
Imagine marking a book as read and closing the tab before the reply arrives. The cache has the last confirmed value, but what happened to the edit? A journal lets the store pick it up again, even if the user was offline when they made it. Choose the writes you want to recover. The store records each one before sending it and keeps the entry until it knows the outcome.
import { createDataStore, indexedDBStorage, serverTransport } from 'octane/data';
import { addBook, receipt, removeBook, setRead } from './contracts.data.ts';
import { data } from './data.tsrx';
import { session } from './session.ts';
export const store = createDataStore({
transport: serverTransport(data),
persist: {
storage: indexedDBStorage(),
partition: session.account,
key: session.cacheKey,
journal: { writes: [addBook, setRead, removeBook], receipt },
},
});Here receipt is the read from When the reply is lost. The list
limits the journal to three kinds of writes. To cover every write your app
declares, use writes from the generated
octane/data/manifest.
When you reopen the shelf, the store finds the unfinished write in the journal
and shows the book as read again. It looks up the receipt to find out
whether the server applied the write, then keeps the edit or rolls it back.
The store never sends the write again. If you were adding a book and the
server assigned its ID, an applied receipt needs to include the created
record as value.
Signing out
When someone switches accounts, give the new account its own store and call
store.retire() on the old one. Retirement clears the values in memory
immediately, ignores replies still on their way, and finishes once the saved
values are deleted. If a component still holds the old store, its reads stay
pending without starting a load, so it has nothing to display. Trying to write
through that store throws DataRetiredError.
import { createDataStore, serverTransport, type DataStore } from 'octane/data';
import { data } from './data.tsrx';
let store: DataStore = createDataStore({ transport: serverTransport(data) });
export async function switchAccount(): Promise<DataStore> {
const old = store;
store = createDataStore({ transport: serverTransport(data) });
await old.retire(); // Resolves once its saved values are deleted.
return store;
}Pass the new store to your DataProvider and key the subtree by account. That
gives the new user a fresh set of components as well as a fresh store.
Closing a window or unmounting a root is a different case. If the user is
still signed in, call store.dispose() when the window or root that owns the
store closes. It frees the values in memory immediately, finishes any saves
already queued and leaves the saved values available for another window or a
later visit. In a shared tab, disposal detaches just that tab.
Retiring the shared store signs the account out across tabs, as described in
One account per browser.
Sharing across tabs
Open the shelf in two tabs. With the setup from Create a store, both tabs share one data worker for the account, called its owner. Each tab keeps a local store, called a replica, so it can render, evaluate views and show your edit as soon as you click. The owner handles the requests and feed connections for all the replicas. When two tabs ask for the same list, it makes one request. When you edit a book, it tells the other tabs about the pending edit, and if the server refuses the edit, every tab rolls it back.
- Tab 1replica store
- Tab 2replica store
- Tab 3replica store
- Data workerserveDataOwner: one owner per account
- ServercreateDataHandler
The data client holds the options that do the worker's work. Give it the
listener for your feeds, so the tabs share one connection, and the
setup of an encrypted cache, so the worker handles every
write to that cache. Its persist is a function of the signed-in account.
// data.client.ts
import { defineDataClient, indexedDBStorage, serverListener, serverTransport } from 'octane/data';
import { data, events } from './data.tsrx';
import { cacheKeyFor } from './cache-key.ts';
export default defineDataClient({
transport: serverTransport(data),
listen: serverListener(events),
persist: (account) => ({
storage: indexedDBStorage(),
partition: account,
key: () => cacheKeyFor(account),
}),
});Here cacheKeyFor stands for a helper you'd write to fetch the signed-in
user's secret. The worker gets the key directly, so the page never has to pass
it across. A tab opens its store with the account and what its page's server
render sent:
import { openDataStore } from 'octane/data/client';
export function openStore(account: string, seed: string | null) {
return openDataStore(account, { seed });
}The tab's store uses the same data client's transport, listen and
persist itself if sharing falls through. It becomes an ordinary store in
any of these cases.
- The browser could start neither a SharedWorker nor a dedicated Worker, so
sharedOwnerreturnednull, or the worker module failed to load. Where only SharedWorker is missing, as in Chrome on Android,sharedOwnerruns the same module as the tab's own dedicated Worker instead. Its requests, feeds and cache still stay off the page's main thread, but that tab doesn't share them with the others. - The tab and the owner came from incompatible deploys. There's more on that below.
- The owner couldn't record the signed-in account. This can happen if IndexedDB is unavailable in the worker.
- The owner stopped responding and the tab couldn't start a replacement.
Both sides use contracts. The replica needs the write declarations to show
edits from other tabs as they happen. The owner checks the full list to make
sure the tabs agree on the contracts they're sharing, and checks what the
server sends against their schemas, so the tabs take each value as it comes. In the meantime, the
replica can hydrate from its page's seed without waiting for the worker.
If you just opened a tab, the server may have sent you a more recent copy of the shelf than the other tabs have. If the HTML came from a cache, your copy might be older. After hydration, the tab shares its seeded values along with the time each one was loaded. All the tabs can use the newer value without another request. The tab also compares the feed position in the page with the worker's position. If they differ, it reloads the reads that feed covers to account for any events it might have missed.
In a test, or when several roots share an owner on one page, you can run the
owner without a worker. Call createDataOwner({ transport, listen }) and pass
a MessagePort to the owner's connect(port) method. One end of a
MessageChannel works, for example. The owner serves the replica over that
port.
Write your own data worker
The data client covers what most apps need. To run more in the worker, such
as the demo faults Shelf injects, write the worker module
yourself and point dataWorker at it instead of dataClient. Give
serveDataOwner the same options, and the build's contracts, so the worker
can check what the server sends against your schemas. In the tab, pass
sharedOwner(account) to createReplica with the store's options and the
same contracts.
// data.worker.ts, built with `dataWorker: 'src/data.worker.ts'`
import { serveDataOwner, serverTransport } from 'octane/data';
import { contracts } from 'octane/data/manifest';
import { data } from './data.tsrx';
serveDataOwner({ transport: serverTransport(data), contracts });// store.ts
import { createReplica, serverTransport, sharedOwner } from 'octane/data';
import { contracts } from 'octane/data/manifest';
import { data } from './data.tsrx';
export const openStore = (account: string) =>
createReplica(sharedOwner(account), { transport: serverTransport(data), contracts });One account per browser, in every tab
Suppose Ada has the shelf open in two tabs. She signs out in one and Grace signs in. The second tab needs to stop showing Ada's books, even if the browser froze it in the background and it missed the sign-out. Any requests still in flight for Ada also belong to her session and have to stay out of Grace's shelf.
The data worker handles this by fencing accounts. It keeps a record in
IndexedDB of the single account signed in on this origin and a generation
number that increases with each sign-in and sign-out. It updates the record
before notifying any tabs, and uses a BroadcastChannel to tell the other
workers about the change. With serveDataOwner, this happens automatically.
Here's how it plays out for Ada and Grace.
- When Grace's tab calls
sharedOwner('grace')while Ada is still recorded, the worker records Grace and retires Ada's stores in every tab. It clears their values, rejects pending requests withDataRetiredErrorand closes their feeds. - If Ada calls
store.retire()on a replica to sign out, it signs her out in all her tabs. The tab keeps asking until the owner confirms, even if the worker is busy or restarting. - Suppose Ada's sign-out arrives after Grace has signed in. The worker checks the generation on the sign-out against the one on record. Ada's request belongs to an earlier generation, so Grace stays signed in.
- While Ada's second tab is frozen, its reads are pending. When it wakes, it asks the owner whether Ada is still signed in before displaying her books again. If her session has ended, the store is retired.
In the tab where the accounts change, open the new account's store and pass it
to your DataProvider as usual. The worker takes care of retiring the old
account's stores in the other tabs.
import { type DataStore } from 'octane/data';
import { openStore } from './store.ts';
export function switchAccount(current: DataStore, next: string): DataStore {
// Recording `next` retires every tab of the old account, this one's store included.
const store = openStore(next, null);
void current.retire();
return store;
}If you host the owner yourself with createDataOwner, pass fence: true to
get the same behavior. By default, a self-hosted owner serves every replica
that connects.
Some apps have a trusted host that decides which account is signed in. In that
setup, pass fence: 'explicit' to serveDataOwner or createDataOwner. The
host grants access with owner.activate(account) and revokes it with
owner.activate(null). A tab can only join the account the host has granted,
and calling retire() on a replica leaves the sign-in under the host's
control.
Each grant has its own persistence partition. The owner erases the previous
partition before publishing the new grant, which starts with an empty cache.
Keep activate out of reach of the tabs. The host must authenticate which
account each port can join and keep one owner per grant.
Different deploys, and crashes
A SharedWorker can outlive the page that started it. After a deploy, someone
opening the shelf might connect to a worker from the previous build. The two
builds can share the owner if their contracts agree. The first tab to connect
supplies the owner's contracts, and the owner compares them when another tab
joins: each contract's kind, name and version, each read's output schema
shape, and the shape of each write's output and each feed's event. If they
differ, the new tab runs with an ordinary store. A schema with a transform
often can't describe its shape, so when a deploy changes what such a schema
accepts or returns, change the contract's version too, and the old worker
won't serve the new tabs. Once all the old tabs
close, the old worker exits and the next tab starts the new worker.
A worker can crash, and a tab can close before it has a chance to disconnect. The tabs and the owner check on each other every five seconds so they can recover in either case.
- If the owner stops answering, the tab hides its values, marks its reads pending and reconnects to a new worker. It asks again for any reads still waiting for an answer. A write may already have reached the server, so the tab marks it uncertain and leaves it for you to settle from its receipt, just as you would after a lost reply. This avoids sending the write twice.
- If a tab stops answering, the owner releases the feed connections it held for that tab. Any writes the tab already sent can finish.
One cache for every tab
With a persist function in the data client (or on serveDataOwner, in a
worker you write yourself), each tab can still look up
saved values and ask to save changes as usual. Those requests go through the
worker, which handles every write to the account's encrypted cache and
journal. That matters when several tabs have the same shelf open.
- If three tabs load the same value, the worker saves it once. The budget applies to the account as a whole.
- Since the worker handles all the saves, a tab with an older copy can't overwrite a newer saved value from another tab.
- When you reload a tab, it asks the worker for the saved values it needs. It can show fresh values without fetching them again.
- The worker keeps one journal for durable writes. After a restart, the first tab to start recovers them, so there's just one receipt lookup per write.
- When the user signs out or another account signs in, the worker clears the previous account's cache.
A tab's own copy of those options comes into play only if it has to run as an
ordinary store. The data client gives it the same ones; in a worker you write
yourself, give createReplica the same storage, partition and key as the
worker so it can use the same cache in that case.
Writes in flight when the worker crashes
Suppose the worker crashes just after you mark a book as read. The edit stays
on screen, but its outcome is uncertain because the server might already have
saved it. If you included the write in the journal, recovery is automatic.
Once the tab reconnects to the new worker, it uses your receipt read to find
out whether to keep the edit or roll it back. It never resends the write.
Every tab displaying the edit asks for its receipt. The worker shares a single request to the server and gives every tab the same answer. If you left the write out of the journal, it stays uncertain until you look up its receipt and settle it yourself, as you would for any lost reply.
Octane and React, one store
If the shelf has both Octane and React components, give them the same store. Each binding subscribes to the store, which owns the values and all the pending edits. A book you mark as read in React shows up as read in Octane at the same time. If the server refuses the edit, both components see the rollback.
- Octane components.tsrx
- React components.tsx
- octane/data/octane
- octane/data/react
- One DataStorevalues, edits, rollbacks
The two bindings export the same hooks and provider with the same behavior. When you move a component between renderers, switching its data binding is a matter of changing the import.
| Hook or component | What it does |
|---|---|
DataProvider | Puts a store in context for the components below it: <DataProvider store={store}>. |
useDataStore() | Returns the store from context: read gives the handles below, write sends a write, and so on. |
useRead(store.read(read, input?)) | Returns the value, suspending until the first one arrives; with { suspend: false }, the live snapshot. |
usePages(pages(store, view, params?)) | Returns the pages so far of a view, or of a read with a cursor, as one list, with more, loadingMore and loadMore. |
useForm(write, key?) | Returns a native form for a write that declares form fields. |
useFeed(listen(store, feed, params?)) | Listens to a feed while mounted, and returns its connection status. |
Use the hooks according to the rules of the renderer you're working in. Octane
identifies a hook by its location in the source, so you can call useRead
inside a condition or after an early return. React relies on call order, so
its usual rules of hooks apply.
An Octane page with a React island
Here the main book list is an Octane component and the “up next” list is a
React component. You can embed the React list with ReactCompat from
octane/react. Pass the page's store into the island and give the island a
React DataProvider of its own.
/** @jsxImportSource react */
// UpNext.tsx — a React component.
import type { DataStore } from 'octane/data';
import { DataProvider, useDataStore, useRead } from 'octane/data/react';
import { setRead, unread } from './contracts.data.ts';
function UpNextList() {
const store = useDataStore();
const list = useRead(store.read(unread), { suspend: false }).value ?? [];
return (
<ul>
{list.map((book) => (
<li key={book.id}>
{book.title}{' '}
<button
type="button"
onClick={() => void store.write(setRead, { id: book.id, read: true }).catch(() => {})}
>
Mark read
</button>
</li>
))}
</ul>
);
}
export function UpNext(props: { store: DataStore }) {
return (
<DataProvider store={props.store}>
<UpNextList />
</DataProvider>
);
}// Page.tsrx — the Octane page that hosts it.
import type { DataStore } from 'octane/data';
import { DataProvider } from 'octane/data/octane';
import { ReactCompat } from 'octane/react';
import { BookList } from './BookList.tsrx';
import { UpNext } from './UpNext.tsx';
export function Page(props: { store: DataStore }) @{
<DataProvider store={props.store}>
@try {
<BookList />
} @pending {
<p>Loading…</p>
}
<ReactCompat>
<UpNext store={props.store} />
</ReactCompat>
</DataProvider>
}There are two providers because each renderer has its own context. They both
receive the very same store object. Click “Mark read” in the React island and
the book moves in the Octane list immediately. If your page is written in
React, you can do the same with OctaneCompat to host Octane components. See
React interop for details.
Errors
When a write fails, the next step depends on what the store knows. The server
might have refused the edit, the reply might have gone missing, or the store
itself might belong to a session that has ended. octane/data gives each
outcome its own error.
| Error | What it means | What to do |
|---|---|---|
DataError | A definitive refusal. The operation did not happen. code says why, data carries details, issues lists validation messages. | Show the reason. A write's edit has already been rolled back. |
DataUncertainError | A write may have reached the server, but its reply was lost. Its edit stays on screen. | Look up its receipt with operationId, then call store.settle. |
DataRetiredError | The store was retired, such as after sign-out. | Use the new account's store. |
A complete example
You can try everything from this guide in
Shelf, a
reading list built with octane/data. The same contracts and server serve
three versions of the page, one in Octane, one in React and one in Octane with
a React island. You can build it with either Vite or Rspack. Try opening the
shelf in two tabs and marking a book as read, then see how the app handles a
lost reply. You can also try it offline or with JavaScript turned off.
API reference
octane/data
| Export | What it is for |
|---|---|
read | Describe a read: name, input, output, entities, tags, fresh, keep, expire, persist, cancel, version. |
write | Describe a write: creates, patches or removes an entity, with draft, serverId, record, form, invalidates and version. |
entity | Name a record type and its key, so every read holding a record shares its fields. |
view | Describe a list by a rule over an entity: where, order, limit, max, and with to join related records. |
feed | Describe server events and the changes each one makes, with the reads it covers and a version. |
DataError | A definitive refusal, with code, data and issues. |
createDataStore | Create a store: transport, seed, seedAge, form, persist, listen, feeds. |
DataUncertainError | A write whose outcome is unknown; settle it by operationId. |
DataRetiredError | Thrown by a retired store. |
httpTransport | Send requests to a handler mounted at a URL. |
serverTransport | Send requests through a module server function that calls handler.serve. |
serverListener | Listen to feeds through a module server function that calls handler.listen. |
webSocketListener | Listen to feeds over a WebSocket served by handler.accept, or an existing socket service. |
pubSubListener | Listen to feeds through a message broker the page already uses. |
listen | Listen to a feed from plain code; returns a handle with getSnapshot and subscribe. |
receive | Apply changes from your own subscription, as a feed event would. |
pages | Read a view, or a read that returns a cursor, a page at a time from plain code. |
indexedDBStorage | Persistent storage in IndexedDB. |
memoryStorage | Storage in memory, for tests and hosts without persistent storage. |
autoBudget | A storage budget sized by the device's memory, data saver and quota. |
createDataOwner | An owner that serves replicas over message ports. |
createReplica | A store whose requests and feeds go through an owner. |
sharedOwner | Connect to the account's owner in the app's data worker: a SharedWorker, else the tab's own dedicated Worker, else null. |
serveDataOwner | Serve an owner to every tab that connects: what the data worker module calls. |
defineDataClient | Declare the app's data client, { transport, listen?, persist? }, as the default export of the module dataClient names. |
contractIdentity | What createReplica compares to tell whether two builds can share an owner; octane/data/manifest exports it as identity. |
The store exposes read, prefetch, write, form, invalidate, settle,
publish, forget, retire, dispose and dehydrate. You can check the
retired flag to see whether the store has been retired.
octane/data/server
| Export | What it is for |
|---|---|
createDataHandler | Serve contracts. Options: context, allowedOrigins, secret, grant. define receives handle and defineHandler, which also serves contracts declared with their function. Returns a fetch-style handler with transport, serve, listen, accept and forms. |
octane/data/octane and octane/data/react
| Export | What it is for |
|---|---|
DataProvider | Provide a store to the components below it. |
useDataStore | Read the store from context. |
useRead | Show a read handle's value, suspending until the first one arrives, or its snapshot with { suspend: false }. |
usePages | Show a pages handle: a view, or a read with a cursor, a page at a time. |
useForm | Render a native form for a write. |
useFeed | Listen to a feed handle while mounted. |