Skip to content

Published collections

A Récit site can publish one JSON file per collection at build time — small sets of JSON documents shared across visitors, such as application settings maintained by site managers or curated lists. Visitors read those files directly from the static site, without an account and without a backend.

This page defines the published collection file contract v1 (@recit/data-store). A static site that writes its collection files in this shape today can connect @recit/data-store/client to a Récit service later with zero file migration.

The contract is published as a Draft 2020-12 JSON Schema at https://recit.dev/schema/v1/published-collection.schema.json (exported as @recit/data-store/published-collection.schema.json). It is generated from the same zod schemas that parsePublishedCollection runs, so the schema and the parser cannot drift.

Path on the site

Every published collection is served as a static JSON file under /collections/ (or <basePath>/collections/ when the site is served under a sub-path such as /docs):

Code
/collections/<name>.json /docs/collections/<name>.json

publishedCollectionPath(name, { basePath }) in @recit/data-store builds this path and checks <name>:

  • <name> must match /^[a-z][a-z0-9-]*$/: a lowercase ASCII letter followed by lowercase letters, digits or hyphens (site-settings, featured-items, presets-2026).
  • Uppercase letters, underscores, slashes and empty names are refused.
  • When basePath is given ("/docs", "/docs/", "docs" or "/"), leading and trailing slashes are normalized so the returned path starts with / and contains no double /.

File shape

A published collection file is a JSON object (PublishedCollection) wrapping an array of documents (PublishedDocument):

FieldTypeRequiredDescription
formatVersion1yesVersion of this file envelope (PUBLISHED_COLLECTION_VERSION).
collectionstringyesCollection name (/^[a-z][a-z0-9-]*$/), matching <name> in /collections/<name>.json.
publishedAtstring (ISO 8601)yesTimestamp when the file was built or exported, with a time zone offset (Z or ±HH:MM).
fetchedAtstring (ISO 8601)noWhen publishCollections fetched the collection from the server, with a time zone offset.
schemaVersionstringnoNon-empty version string declared by the site for its own document body schema ("1", "2026-11").
documentsPublishedDocument[]yesList of documents in the collection (may be empty []).

Each entry in documents has the following fields:

FieldTypeRequiredDescription
idstringyesNon-empty identifier, unique within documents[] (parsePublishedCollection refuses duplicates).
bodyunknown (JSON)yesDocument payload, validated by the collection's own schema in the site — never by @recit/data-store.
updatedAtstring (ISO 8601)yesLast modification timestamp of the document, with a time zone offset (Z or ±HH:MM).
authorstringnoOptional non-empty identifier or display name of the author who wrote the document.

Schema of body

@recit/data-store validates the envelope and document metadata (id, updatedAt, author), and leaves body as unknown. The schema of body lives in the site alongside its pages and application code: the site parses each doc.body with its own zod or JSON Schema validator.

Example

/collections/site-settings.json:

JSONJSON
{ "formatVersion": 1, "collection": "site-settings", "publishedAt": "2026-11-12T10:00:00Z", "schemaVersion": "1", "documents": [ { "id": "banner", "body": { "headline": "Lorem ipsum dolor sit amet", "enabled": true }, "updatedAt": "2026-11-12T09:30:00Z", "author": "Lorem Ipsum" }, { "id": "defaults", "body": { "density": "comfortable", "maxItems": 12 }, "updatedAt": "2026-11-11T17:45:00+01:00" } ] }

Reading and validating a published collection in a static site:

TypeScriptTypeScript
import { parsePublishedCollection, publishedCollectionPath, } from "@recit/data-store"; import * as z from "zod"; const BannerSchema = z.object({ headline: z.string(), enabled: z.boolean(), }); const response = await fetch(publishedCollectionPath("site-settings")); const file = parsePublishedCollection(await response.json(), { expectedName: "site-settings", }); const bannerDoc = file.documents.find((doc) => doc.id === "banner"); const banner = bannerDoc ? BannerSchema.parse(bannerDoc.body) : undefined;

Passing { expectedName } checks that the file's collection field matches the <name> requested from /collections/<name>.json and throws a clear error otherwise. When the site is served under a sub-path (basePath: "/docs"), pass { basePath: "/docs" } to publishedCollectionPath to obtain "/docs/collections/site-settings.json".

Versioning rules (formatVersion)

  1. formatVersion is required and checked first. parsePublishedCollection expects formatVersion: 1. A missing or unknown formatVersion throws an error naming both the version read from the file and the expected version (1). Only a breaking change to the envelope increments formatVersion.
  2. Unknown fields are preserved (passthrough). PublishedCollectionSchema uses a loose object at the file level (and on document entries): if a future minor release adds optional metadata to the envelope, existing readers keep working and preserve those fields untouched.
  3. schemaVersion belongs to the site. When a site evolves the shape of body inside one of its collections, it can record that version in schemaVersion without changing formatVersion.

Reading with @recit/data-store/client

createDataStoreClient reads public collections with an in-memory ETag cache and automatic fallback to the published /collections/<name>.json file:

TypeScriptTypeScript
import { createDataStoreClient } from "@recit/data-store/client"; import * as z from "zod"; const BannerSchema = z.object({ headline: z.string(), enabled: z.boolean(), }); const client = createDataStoreClient({ basePath: "/docs", timeoutMs: 3_000, server: { url: "https://api.example.com", structureId: "struct-lorem", }, }); const { collection, source, fallbackReason } = await client.readCollection("site-settings"); const bannerDoc = collection.documents.find((doc) => doc.id === "banner"); const banner = bannerDoc ? BannerSchema.parse(bannerDoc.body) : undefined;

Resolution order of client.readCollection(name, { signal }):

  1. Server first (when server is configured). Queries GET <server.url>/v1/structures/<structureId>/collections/<name> within timeoutMs (3000 ms by default). Once that client instance holds a server copy (kept only when the response carried an ETag), it asks for ?since=<publishedAt of the copy> with If-None-Match: 304 Not Modified reuses the copy, and a 200 partial response is merged into it (changed documents replaced, documents missing from partial.ids removed, order of partial.ids kept). A partial response that cannot be merged triggers one full read. A partial response whose partial.since is not the copy's publishedAt, or that arrives without a copy, is never taken for a whole collection. Returns source: "server".
  2. Published JSON fallback (/collections/<name>.json). When server is omitted, or when the server request fails, exceeds timeoutMs, returns 404 or 5xx, or returns an invalid payload, reads <basePath>/collections/<name>.json and returns source: "published" along with fallbackReason (CollectionFallbackReason: "no_server", "unreachable", "server_error", "not_found" or "invalid").

Partial reads

On the server read route (GET /v1/structures/<structureId>/collections/<name>?since=<ISO 8601 date-time with offset>), passing since keeps the v1 PublishedCollection envelope (formatVersion, collection, publishedAt, documents) with only documents written on the server strictly after since (400 invalid_since on malformed timestamps). Every write to a collection advances publishedAt by at least one millisecond, and document writes stamp the document with that publishedAt. The since filter compares that internal write time (never served) rather than updatedAt, while each returned document keeps its updatedAt as written. Passing the publishedAt of the last read as since never misses a write, regardless of updatedAt. Partial responses also add partial: { since, ids } with the received since string and every current document identifier in sorted order, so readers can detect deletions without server tombstones. Omitting since returns the full collection with identical bytes and ETag. A partial response carries the ETag of the full collection. Sending If-None-Match with that ETag on a ?since= URL returns 304 when nothing has changed. Collection writes cap each collection at 500 documents and 1 MiB (413 collection_too_large), summing the UTF-8 bytes of each document's id, body, extra fields and author. Server document writes require any supplied updatedAt to carry a UTC year in 1970..9999 (400 invalid_body).

Subscribing

client.subscribe(name, listener, options?) reads the collection immediately and polls every options.intervalMs milliseconds (DEFAULT_SUBSCRIBE_INTERVAL_MS = 30_000 by default, 5_000 minimum, or throws a RangeError). Timers are chained with setTimeout so two reads never overlap.

  • Event stream (options.stream). By default (options.stream !== false), subscribe also opens GET <server.url>/v1/structures/<structureId>/collections/<name>/events once the first read starts. This requires server on the client and an EventSource constructor (options.EventSource on createDataStoreClient, or globalThis.EventSource); otherwise, subscribe uses polling alone. The stream never carries content, and interval polling stays active as a fallback. A change event sends { "etag": "\"…\"" } and triggers an immediate reread when that etag differs from the previous snapshot; gone ({}) always triggers an immediate reread. If a read is already running, the reread runs as soon as it finishes.
  • Change detection. Revalidations reuse the client's cached ETag (304 Not Modified). listener(result) runs on the first delivered read and whenever the collection changes — by ETag when both reads carry one, or by publishedAt, schemaVersion and serialized documents captured at read time (mutating result.collection.documents in place does not cause a false change).
  • Server-to-static fallback guard. Before any server read succeeds, source: "published" is delivered normally. Once a turn has served source: "server", a later fallback to source: "published" (transient outage or timeout) is ignored: listener is not called and the last server state is kept until a later read reaches the server again.
  • Hidden tabs. Scheduled polls and stream events while document.visibilityState === "hidden" are skipped. Returning to the tab does not trigger an immediate read; the next read runs on the next scheduled interval (up to intervalMs later).
  • Errors and cancellation. options.onError(error) (unknown) receives DataStoreReadError, DataStoreStreamError, any other read error, and any error thrown by listener. DataStoreStreamError (with collection: string) is reported on malformed change payloads or when the stream closes permanently (readyState === 2, such as 404, 429 or 503). Transient disconnects handled by EventSource reconnection (with Last-Event-ID, including the server's five-minute close) stay silent, and polling continues even if the stream closes or onError throws. Passing options.signal or calling unsubscribe() closes the stream, aborts any in-flight read and stops future polls.

Writing with an account

Public reads (readCollection and subscribe) require no account and work with server.url and server.structureId alone. Authenticated document writes (client.writeDocument and client.deleteDocument) add two options on createDataStoreClient:

  • server.organizationId — non-empty organization identifier owning server.structureId (validated at client creation like structureId: trimmed, non-empty, neither "." nor "..", and containing no "/", "\\" or NUL).
  • getAccessToken (() => string | undefined | Promise<string | undefined>, optional) — called inside the timeoutMs budget (and respecting opts.signal). If it throws or rejects (other than an abort on opts.signal, which rethrows signal.reason), the call rejects with DataStoreWriteError (code: "token_error"). When it returns a non-empty token (printable ASCII without whitespace, /^[\x21-\x7E]+$/), server.url must use https: (or http: on a loopback host: localhost, 127.0.0.1, or [::1]) with no credentials (user:pass@), ?query, or #fragment (otherwise DataStoreWriteError with code: "invalid_request" is thrown before any request), and the client sends Authorization: Bearer <token> with credentials: "omit"; when omitted or returning undefined / "", the client sends credentials: "include" so a same-origin session cookie authenticates the request.
TypeScriptTypeScript
import { createDataStoreClient, DataStoreWriteError, } from "@recit/data-store/client"; const client = createDataStoreClient({ basePath: "/docs", server: { url: "https://api.example.com", organizationId: "org-lorem", structureId: "struct-lorem", }, getAccessToken: () => accessToken, // omit on the same origin to use the session cookie }); const stored = await client.writeDocument( "site-settings", "banner", { headline: "Lorem ipsum dolor sit amet", enabled: true }, { updatedAt: "2026-11-21T10:00:00Z" }, ); await client.deleteDocument("site-settings", "banner");

writeDocument(name, docId, body, opts?) (WriteDocumentOptions: { signal?, updatedAt? }) sends PUT <server.url>/v1/products/collections/organizations/<organizationId>/structures/<structureId>/collections/<name>/documents/<docId> with { body, updatedAt? } and redirect: "error" within timeoutMs, validates the returned PublishedDocument (200, including id === docId, updatedAt ISO 8601 with time zone offset, and optional non-empty author), and returns it. deleteDocument(name, docId, opts?) (DeleteDocumentOptions: { signal? }) sends DELETE to the same URL with redirect: "error" within timeoutMs (204), so neither PUT nor DELETE ever follows an HTTP redirect. Before any request is sent, name is checked with parseCollectionName, docId must be 1 to 200 characters, neither "." nor "..", and contain no "/" or NUL, and body on writeDocument must be JSON-serializable (JSON.stringify must neither return undefined — as for undefined, a function, or a symbol — nor throw, as for a bigint or circular reference). After a successful write or delete, the client drops its cached server copy of name so the next readCollection fetches fresh data.

Write error codes

Write failures throw DataStoreWriteError (code: DataStoreWriteErrorCode, optional HTTP status?: number, collection: CollectionName, docId: string). When the server returns a JSON { error, message } payload, DataStoreWriteError.message forwards message without echoing the document body. Aborting opts.signal rethrows signal.reason directly instead of wrapping it in DataStoreWriteError.

codeCondition
"no_account_server"server or server.organizationId is missing (no request sent).
"invalid_request"Invalid name or docId, non-JSON-serializable body, invalid bearer token, or unsafe server.url for a bearer token before the request, or HTTP 400 (invalid_body, invalid_document_id, body_too_large).
"token_error"getAccessToken threw or rejected before any request was sent (when opts.signal was not aborted).
"unauthorized"HTTP 401 (missing or expired session cookie or bearer token).
"forbidden"HTTP 403 (disallowed request Origin or insufficient role in the organization).
"not_found"HTTP 404 (missing document on DELETE, unknown structure, or an organization the account cannot access).
"conflict"HTTP 409.
"too_large"HTTP 413 (collection_too_large).
"rate_limited"HTTP 429.
"server_error"HTTP 5xx.
"unreachable"Network error, redirect refused (redirect: "error"), or timeoutMs exceeded (including while awaiting getAccessToken).
"invalid_response"200 response whose payload is not a valid PublishedDocument with id === docId (body present, updatedAt ISO 8601 with time zone offset, optional non-empty author), or an unexpected HTTP status.
"queue_full"Offline write queue (@recit/data-store/queue) already holds maxSize pending entries and the call targets a distinct (name, docId) (existing entries are kept untouched).

Offline write queue

@recit/data-store/queue provides createOfflineWriteQueue(client, options?) in its own subpath so @recit/data-store/client stays small for read-only sites (@recit/data-store does not re-export it):

TypeScriptTypeScript
import { createOfflineWriteQueue } from "@recit/data-store/queue"; const queue = createOfflineWriteQueue(client, { storage: localStorage, onFlush: ({ written, failed, pending }) => { void written; void failed; void pending; }, }); const outcome = await queue.writeDocument( "site-settings", "banner", { headline: "Lorem ipsum dolor sit amet", enabled: true }, { updatedAt: "2026-11-21T10:00:00Z" }, ); queue.dispose();
  • Queueing and coalescing. When queue.pending() (readonly QueuedOperation[], each stamped with an ISO 8601 queuedAt from options.now ?? (() => new Date())) is empty, queue.writeDocument(name, docId, body, { updatedAt? }) and queue.deleteDocument(name, docId) call client directly and resolve to { status: "written", document } or { status: "deleted" } (QueuedWriteOutcome). A DataStoreWriteError with code: "unreachable" enqueues the operation and resolves to { status: "queued", pending }; any other error is rethrown without queueing. When operations are already pending, a new call appends behind them in order and attempts flush(). An operation for a (name, docId) already in the queue replaces the earlier entry at the newest position (last operation wins). Adding a distinct (name, docId) when the queue is at options.maxSize (100 by default) throws DataStoreWriteError (code: "queue_full") without losing or overwriting queued entries.
  • Replay and server rejections (flush). queue.flush() replays pending operations one at a time in order (concurrent flush() calls share the in-flight promise) and passes the FlushResult ({ written, failed, pending }) to options.onFlush. On the first "unreachable" error, flush() stops and leaves that operation and everything behind it in the queue. Any other DataStoreWriteError (400, 401, 403, 404, 409, 413…) removes that operation from the queue and appends { operation, error } to failed. Document bodies never appear in error messages. When options.autoFlush is not false (true by default) and globalThis.addEventListener is available, online events call flush() automatically with no timer; queue.dispose() removes the listener.
  • Storage (DataStoreQueueStorage). Storage defaults to memory only, so nothing leaves the page unless options.storage ({ getItem, setItem, removeItem }, satisfied by globalThis.localStorage) is passed. With storage, the queue is read on creation from options.storageKey ("recit:data-store:queue" by default — invalid JSON or entries not matching QueuedOperation are ignored and reset to empty), rewritten on every change, and cleared with removeItem when empty. Storage errors (such as quota or denied access) never fail a call; the queue continues in memory. Passing localStorage keeps queued document bodies on the device until they are flushed or cleared.

Publishing server collections at build time

publishCollections in @recit/data-store/publish (Node.js) copies public collections from a Récit server into <outDir>/collections/<name>.json during a site build. This keeps the static fallback current.

Call it in a site's prebuild script (for example scripts/sync-collections.mjs, writing to public):

JavascriptJavaScript
import { publishCollections } from "@recit/data-store/publish"; const outcomes = await publishCollections({ server: { url: "https://api.example.com", structureId: "struct-lorem", }, token: process.env.RECIT_STRUCTURE_TOKEN, // optional build secret, never committed collections: ["site-settings", "featured-items"], outDir: "public", });

Without a script, recit collections publish does the same from the command line, the token read from RECIT_STRUCTURE_TOKEN only:

TerminalBash
recit collections publish site-settings featured-items \ --server https://api.example.com --structure struct-lorem --output public

It prints one line per collection (written, kept with its reason, or removed) and exits with 0 when a collection keeps its previous file, so a build goes on with its fallback; --strict makes that exit 1, and --json prints the outcomes as publishCollections returns them. The command needs @recit/data-store next to recit (npm install @recit/data-store), an optional package the CLI names when it is missing.

Options are validated upfront before any request runs:

  • Every entry in collections is checked with parseCollectionName (collections absent from options.collections are never read or deleted, even if the server lists them as "reserved").
  • token set to undefined, "", or whitespace only (such as an unset CI secret in process.env.RECIT_STRUCTURE_TOKEN) is ignored and treated as omitted. Any other token is checked as-is (without trimming) against /^[\x21-\x7E]+$/ (printable ASCII without whitespace; spaces, newlines, or invisible characters such as U+200B throw before any request).
  • When a non-empty token is supplied, server.url must use https: (or http: on a loopback host: localhost, 127.0.0.1, or [::1]) and contain no credentials (user:pass@), ?query, or #fragment; otherwise publishCollections throws before any request. Without a non-empty token, server.url rules are unchanged.

When a non-empty token (the structure's write bearer token, read from a build secret and never committed) is supplied, publishCollections first lists collection visibilities from GET <server.url>/v1/structures/<structureId>/collections (Authorization: Bearer <token>, credentials: "omit", redirect: "error" so the token never follows a redirect, with the walk bounded by timeoutMs), expecting { "collections": [{ "name": string, "visibility": "public" | "reserved" }, …], "nextCursor": string | null } (extra fields such as publishedAt, as well as malformed entries in collections, are ignored). On the server, GET /v1/structures/<structureId>/collections orders collections by name and accepts optional limit (1..200, 100 by default) and opaque cursor query parameters (400 { "error": "invalid_query" } when repeated, out of range, or undecodable), returning nextCursor: null on the last page. publishCollections requests ?limit=200 and, while nextCursor is a string, follows ?limit=200&cursor=<URL-encoded nextCursor> for up to 50 pages, merging valid entries across pages; the walk stops when nextCursor is null or absent, when a cursor repeats (without re-requesting it), or after 50 pages, keeping the entries gathered so far. Any redirect error, non-200 status, network error, timeout, or invalid payload on any page discards the entire visibility listing so the run proceeds as when token is omitted, and the token never appears in outcomes or error messages. Without a non-empty token, no visibility list request is sent.

Then, for each collection name in options.collections in order:

  • Removed (status: "removed"). When a non-empty token was supplied and the visibility list explicitly reports the collection as "reserved", publishCollections skips the public read, deletes <outDir>/collections/<name>.json if it exists (ENOENT ignored), and returns { collection, status: "removed", path, reason: "reserved" }. A plain 404 on the public read never deletes a file, because a collection may exist only as a static file.
  • Written (status: "written"). Otherwise ("public", absent from the list, or without a visibility list), publishCollections requests the full GET <server.url>/v1/structures/<structureId>/collections/<name> within timeoutMs (3000 ms by default). On a valid 200 response, <outDir>/collections/<name>.json is written atomically with the received envelope plus a top-level fetchedAt ISO 8601 timestamp (now().toISOString()), without partial. Readers (parsePublishedCollection and @recit/data-store/client) keep unknown top-level fields and read fetchedAt as-is. Returns { collection, status: "written", path, fetchedAt, documents }.
  • Existing file kept (status: "kept"). If the public read is unreachable or times out ("unreachable"), returns 5xx ("server_error"), returns 404 ("not_found"), or returns an invalid response ("invalid"), any existing <outDir>/collections/<name>.json file is left as-is and no exception is thrown. Returns { collection, status: "kept", path, reason }. Disk write and delete errors still throw.

Phase 1 (static) and Phase 2 (with a server)

Collections are designed around Récit's offline-first principle — nothing breaks when a server is unreachable:

  • Phase 1 — static only. The site generates or commits public/collections/<name>.json, serves it with the static build, and reads it through createDataStoreClient() (without server) or parsePublishedCollection. No server and no account are needed.
  • Phase 2 — with a Récit service. When the site configures server on createDataStoreClient, reads query the service first (with a bounded timeout and ETag/304 revalidation) and fall back transparently to the published /collections/<name>.json file with fallbackReason whenever the service is down, slow or unreachable. Authenticated writes and build-time refresh of /collections/<name>.json keep the static fallback current, and files written in Phase 1 are read as-is in Phase 2 without migration.

What published collections are not

Published collections intentionally stay small and focused:

  • Not a general-purpose database. There are no joins, ad-hoc queries, pagination cursors or high-volume transactional tables. A collection holds a modest set of JSON documents (settings, presets, curated entries) read often and written rarely.
  • Not file or media storage. Do not embed binary blobs or large assets in body; store media as regular static files or external URLs and reference their path in body.
  • Not a real-time channel. Readers see published files and HTTP responses, not live multi-user streams.