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/). A static site
that writes its collection files in this shape today can connect @recit/ to a
Récit service later with zero file migration.
The contract is published as a Draft 2020-12 JSON Schema at
https:// (exported as
@recit/). 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>/ when the site is served under a sub-path such as /docs):
Code
publishedCollectionPath(name, { basePath }) in @recit/ builds this path and checks
<name>:
<name>must match/^[a-: a lowercase ASCII letter followed by lowercase letters, digits or hyphens (z][a- z0- 9- ]*$/ site-,settings featured-,items presets-2026).- Uppercase letters, underscores, slashes and empty names are refused.
- When
basePathis 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):
| Field | Type | Required | Description |
|---|---|---|---|
formatVersion | 1 | yes | Version of this file envelope (PUBLISHED_). |
collection | string | yes | Collection name (/^[a-), matching <name> in /collections/. |
publishedAt | string (ISO 8601) | yes | Timestamp when the file was built or exported, with a time zone offset (Z or ±HH:MM). |
fetchedAt | string (ISO 8601) | no | When publishCollections fetched the collection from the server, with a time zone offset. |
schemaVersion | string | no | Non-empty version string declared by the site for its own document body schema ("1", "2026-11"). |
documents | PublishedDocument[] | yes | List of documents in the collection (may be empty []). |
Each entry in documents has the following fields:
| Field | Type | Required | Description |
|---|---|---|---|
id | string | yes | Non-empty identifier, unique within documents[] (parsePublishedCollection refuses duplicates). |
body | unknown (JSON) | yes | Document payload, validated by the collection's own schema in the site — never by @recit/. |
updatedAt | string (ISO 8601) | yes | Last modification timestamp of the document, with a time zone offset (Z or ±HH:MM). |
author | string | no | Optional non-empty identifier or display name of the author who wrote the document. |
Schema of body
@recit/ 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/:
JSON
Reading and validating a published collection in a static site:
TypeScript
Passing { expectedName } checks that the file's collection field matches the <name> requested
from /collections/ and throws a clear error otherwise. When the site is served under a
sub-path (basePath:), pass { basePath: to publishedCollectionPath to obtain
"/.
Versioning rules (formatVersion)
formatVersionis required and checked first.parsePublishedCollectionexpectsformatVersion:. A missing or unknown1 formatVersionthrows an error naming both the version read from the file and the expected version (1). Only a breaking change to the envelope incrementsformatVersion.- Unknown fields are preserved (
passthrough).PublishedCollectionSchemauses 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. schemaVersionbelongs to the site. When a site evolves the shape ofbodyinside one of its collections, it can record that version inschemaVersionwithout changingformatVersion.
Reading with @recit/ data- store/ client
createDataStoreClient reads public collections with an in-memory ETag cache and automatic
fallback to the published /collections/ file:
TypeScript
Resolution order of client.:
- Server first (when
serveris configured). QueriesGET <server.withinurl>/ v1/ structures/ <structureId>/ collections/ <name> timeoutMs(3000ms by default). Once that client instance holds a server copy (kept only when the response carried anETag), it asks for?since=with<publishedAt of the copy> If-:None- Match 304 Not Modifiedreuses the copy, and a200partial response is merged into it (changed documents replaced, documents missing frompartial.idsremoved, order ofpartial.idskept). A partial response that cannot be merged triggers one full read. A partial response whosepartial.is not the copy'ssince publishedAt, or that arrives without a copy, is never taken for a whole collection. Returnssource:."server" - Published JSON fallback (
/collections/). When<name>.json serveris omitted, or when the server request fails, exceedstimeoutMs, returns404or5xx, or returns an invalid payload, reads<basePath>/and returnscollections/ <name>.json source:along with"published" fallbackReason(CollectionFallbackReason:"no_server","unreachable","server_,error" "not_found"or"invalid").
Partial reads
On the server read route
(GET /),
passing since keeps the v1 PublishedCollection envelope (formatVersion, collection,
publishedAt, documents) with only documents written on the server strictly after since
(400 invalid_ 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: 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- 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_), 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_).
Subscribing
client. reads the collection immediately and polls every
options. milliseconds (DEFAULT_ by default, 5_000
minimum, or throws a RangeError). Timers are chained with setTimeout so two reads never overlap.
- Event stream (
options.). By default (stream options.),stream !== false subscribealso opensGET <server.once the first read starts. This requiresurl>/ v1/ structures/ <structureId>/ collections/ <name>/ events serveron the client and anEventSourceconstructor (options.onEventSource createDataStoreClient, orglobalThis.); otherwise,EventSource subscribeuses polling alone. The stream never carries content, and interval polling stays active as a fallback. Achangeevent sends{ "etag":and triggers an immediate reread when that"\"…\"" } etagdiffers 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 — byETagwhen both reads carry one, or bypublishedAt,schemaVersionand serializeddocumentscaptured at read time (mutatingresult.in place does not cause a false change).collection. documents - Server-to-static fallback guard. Before any server read succeeds,
source:is delivered normally. Once a turn has served"published" source:, a later fallback to"server" source:(transient outage or timeout) is ignored:"published" listeneris 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.are skipped. Returning to the tab does not trigger an immediate read; the next read runs on the next scheduled interval (up tovisibilityState === "hidden" intervalMslater). - Errors and cancellation.
options.(onError(error) unknown) receivesDataStoreReadError,DataStoreStreamError, any other read error, and any error thrown bylistener.DataStoreStreamError(withcollection:) is reported on malformedstring changepayloads or when the stream closes permanently (readyState ===, such as2 404,429or503). Transient disconnects handled byEventSourcereconnection (withLast-, including the server's five-minute close) stay silent, and polling continues even if the stream closes orEvent- ID onErrorthrows. Passingoptions.or callingsignal 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. alone. Authenticated document writes (client. and
client.) add two options on createDataStoreClient:
server.— non-empty organization identifier owningorganizationId server.(validated at client creation likestructureId structureId: trimmed, non-empty, neither"."nor"..", and containing no"/","\\"orNUL).getAccessToken(() =, optional) — called inside the> string | undefined | Promise<string | undefined> timeoutMsbudget (and respectingopts.signal). If it throws or rejects (other than an abort onopts.signal, which rethrowssignal.), the call rejects withreason DataStoreWriteError(code:). When it returns a non-empty token (printable ASCII without whitespace,"token_ error" /^[\x21-),\x7E]+$/ server.urlmust usehttps:(orhttp:on a loopback host:localhost,127.0.0.1, or[::1]) with no credentials (user:pass@),?query, or#fragment(otherwiseDataStoreWriteErrorwithcode:is thrown before any request), and the client sends"invalid_ request" Authorization:withBearer <token> credentials:; when omitted or returning"omit" undefined/"", the client sendscredentials:so a same-origin session cookie authenticates the request."include"
TypeScript
writeDocument(name, docId, body, opts? (WriteDocumentOptions: { signal?) sends
PUT <server.
with { body, updatedAt? and redirect: 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:
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. 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:, optional HTTP
status?:, collection:, docId:). When the server returns a JSON
{ error, message } payload, DataStoreWriteError. forwards message without echoing the
document body. Aborting opts.signal rethrows signal. directly instead of wrapping it in
DataStoreWriteError.
code | Condition |
|---|---|
"no_ | server or server. is missing (no request sent). |
"invalid_ | 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_, body_). |
"token_ | 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_). |
"rate_ | HTTP 429. |
"server_ | HTTP 5xx. |
"unreachable" | Network error, redirect refused (redirect:), or timeoutMs exceeded (including while awaiting getAccessToken). |
"invalid_ | 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/) already holds maxSize pending entries and the call targets a distinct (name, docId) (existing entries are kept untouched). |
Offline write queue
@recit/ provides createOfflineWriteQueue(client, options? in its own subpath so
@recit/ stays small for read-only sites (@recit/ does not re-export
it):
TypeScript
- Queueing and coalescing. When
queue.(pending() readonly QueuedOperation[], each stamped with an ISO 8601queuedAtfromoptions.) is empty,now ?? (() = > new Date()) queue.andwriteDocument(name, docId, body, { updatedAt? }) queue.calldeleteDocument(name, docId) clientdirectly and resolve to{ status:or"written", document } { status:("deleted" } QueuedWriteOutcome). ADataStoreWriteErrorwithcode:enqueues the operation and resolves to"unreachable" { status:; any other error is rethrown without queueing. When operations are already pending, a new call appends behind them in order and attempts"queued", pending } 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 atoptions.(maxSize 100by default) throwsDataStoreWriteError(code:) without losing or overwriting queued entries."queue_ full" - Replay and server rejections (
flush).queue.replays pending operations one at a time in order (concurrentflush() flush()calls share the in-flight promise) and passes theFlushResult({ written, failed, pending }) tooptions.. On the firstonFlush "unreachable"error,flush()stops and leaves that operation and everything behind it in the queue. Any otherDataStoreWriteError(400,401,403,404,409,413…) removes that operation from the queue and appends{ operation, error }tofailed. Document bodies never appear in error messages. Whenoptions.is notautoFlush false(trueby default) andglobalThis.is available,addEventListener onlineevents callflush()automatically with no timer;queue.removes the listener.dispose() - Storage (
DataStoreQueueStorage). Storage defaults to memory only, so nothing leaves the page unlessoptions.(storage { getItem, setItem, removeItem }, satisfied byglobalThis.) is passed. WithlocalStorage storage, the queue is read on creation fromoptions.(storageKey "recit:by default — invalid JSON or entries not matchingdata- store: queue" QueuedOperationare ignored and reset to empty), rewritten on every change, and cleared withremoveItemwhen empty. Storage errors (such as quota or denied access) never fail a call; the queue continues in memory. PassinglocalStoragekeeps queued document bodies on the device until they are flushed or cleared.
Publishing server collections at build time
publishCollections in @recit/ (Node.js) copies public collections from a Récit
server into <outDir>/ during a site build. This keeps the static fallback
current.
Call it in a site's prebuild script (for example scripts/, writing to
public):
JavaScript
Without a script, recit collections publish does the same from the command line, the token read
from RECIT_ only:
Bash
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/ next to recit (npm install @), an optional
package the CLI names when it is missing.
Options are validated upfront before any request runs:
- Every entry in
collectionsis checked withparseCollectionName(collections absent fromoptions.are never read or deleted, even if the server lists them ascollections "reserved"). tokenset toundefined,"", or whitespace only (such as an unset CI secret inprocess.) is ignored and treated as omitted. Any otherenv. RECIT_ STRUCTURE_ TOKEN tokenis checked as-is (without trimming) against/^[\x21-(printable ASCII without whitespace; spaces, newlines, or invisible characters such as\x7E]+$/ U+200Bthrow before any request).- When a non-empty
tokenis supplied,server.urlmust usehttps:(orhttp:on a loopback host:localhost,127.0.0.1, or[::1]) and contain no credentials (user:pass@),?query, or#fragment; otherwisepublishCollectionsthrows before any request. Without a non-emptytoken,server.urlrules 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. (Authorization:,
credentials:, redirect: so the token never follows a redirect, with the walk
bounded by timeoutMs), expecting
{ "collections":
(extra fields such as publishedAt, as well as malformed entries in collections, are ignored). On
the server, GET / orders collections by name and accepts
optional limit (1..200, 100 by default) and opaque cursor query parameters (400
{ "error": when repeated, out of range, or undecodable), returning
nextCursor: on the last page. publishCollections requests ?limit=200 and, while
nextCursor is a string, follows ?limit= 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. in order:
- Removed (
status:). When a non-empty"removed" tokenwas supplied and the visibility list explicitly reports the collection as"reserved",publishCollectionsskips the public read, deletes<outDir>/if it exists (collections/ <name>.json ENOENTignored), and returns{ collection, status:. A plain"removed", path, reason: "reserved" } 404on the public read never deletes a file, because a collection may exist only as a static file. - Written (
status:). Otherwise ("written" "public", absent from the list, or without a visibility list),publishCollectionsrequests the fullGET <server.withinurl>/ v1/ structures/ <structureId>/ collections/ <name> timeoutMs(3000ms by default). On a valid200response,<outDir>/is written atomically with the received envelope plus a top-levelcollections/ <name>.json fetchedAtISO 8601 timestamp (now().), withouttoISOString() partial. Readers (parsePublishedCollectionand@recit/) keep unknown top-level fields and readdata- store/ client fetchedAtas-is. Returns{ collection, status:."written", path, fetchedAt, documents } - Existing file kept (
status:). If the public read is unreachable or times out ("kept" "unreachable"), returns5xx("server_), returnserror" 404("not_found"), or returns an invalid response ("invalid"), any existing<outDir>/file is left as-is and no exception is thrown. Returnscollections/ <name>.json { collection, status:. Disk write and delete errors still throw."kept", path, reason }
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/, serves it with the static build, and reads it throughcollections/ <name>.json createDataStoreClient()(withoutserver) orparsePublishedCollection. No server and no account are needed. - Phase 2 — with a Récit service. When the site configures
serveroncreateDataStoreClient, reads query the service first (with a bounded timeout andETag/304revalidation) and fall back transparently to the published/collections/file with<name>.json fallbackReasonwhenever the service is down, slow or unreachable. Authenticated writes and build-time refresh of/collections/keep the static fallback current, and files written in Phase 1 are read as-is in Phase 2 without migration.<name>.json
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 inbody. - Not a real-time channel. Readers see published files and HTTP responses, not live multi-user streams.