@nextgensoftwares/folio-server-node
The reference Folio document server for Node 22+: the REST sync protocol on node:http (no framework), collaboration over WebSocket (ws), persistence behind a DocStorage interface (files + an append-only log by default), brotli/gzip, keep-alive, optional HTTP/2. Guide: Real networks.
import { toProseMirrorSchema } from '@nextgensoftwares/folio-editor';
import { createFolioServer, FileStorage } from '@nextgensoftwares/folio-server-node';
const app = createFolioServer({
schema: toProseMirrorSchema(hostSchema), // the same schema as the clients
storage: new FileStorage('/var/lib/folio'),
cors: ['https://app.example.com'],
authorize: (req, docId, action) => canAccess(req, docId, action),
});
await app.listen(8787, '0.0.0.0');The server's schema must be the clients' full schema. Build it from the standard schema plus every enabled plugin's Node-safe /schema entry (no React, no DOM), so the server, live collab and the editors agree:
import { standardSchema } from '@nextgensoftwares/folio-model';
import { schema as code } from '@nextgensoftwares/folio-plugin-code/schema';
import { schema as layers } from '@nextgensoftwares/folio-plugin-layers/schema';
import { schema as toc } from '@nextgensoftwares/folio-plugin-toc/schema';
// ...one per plugin the editor uses (every @nextgensoftwares/folio-plugin-* has `/schema`)
const hostSchema = [code, layers, toc].reduce((s, part) => s.extend(part), standardSchema);A push that uses a node, mark or attribute the server's schema lacks is refused with 422 { rejected: 'unsupported', error }; the error names the types (e.g. node type "drawing"), the client stops with that message (SyncStatus.reason / CollabStatus.reason === 'unsupported', no auto-resync) instead of reporting a divergence. PUT /docs/:id refuses such documents with 400 and the same message. node tools/check-schema-entries.mjs (after pnpm build) checks every /schema entry stays Node-safe.
Server
| Export | Signature | Description |
|---|---|---|
createFolioServer | (opts: FolioServerOptions) => FolioServer | REST routes + WebSocket collab + storage; listen(port?, host?), close() (snapshots dirty documents) |
type FolioServerOptions | schema, storage? (MemoryStorage), cors? (true or origins), collab? (false or CollabOptions), tls? ({ key, cert }: HTTP/2 with HTTP/1.1 fallback), exposeStats? (memory and loaded documents in /health; dev only), fallback? (host routes), plus RouteOptions and PersistOptions | |
type FolioServer | { server, documents, collab?, listen, close } | |
createRoutes | (docs, opts?: RouteOptions) => (req, res) => Promise<boolean> | the protocol routes alone, for mounting in another node:http app; resolves false when the URL isn't Folio's |
type RouteOptions | authorize?, roleOf? (RoleOf: each caller's role and user id), suggestions?, allowCreate? (false), maxBodyBytes? (4 MB), maxPullSteps? (2000), chunkCache? ('private' or 'public'), compressedCacheBytes? (64 MB), onCommit?(docId), plus EditRouteOptions | |
type EditRouteOptions | allowEdits? (false: POST /docs/:id/edit is 404), editOrigin?(req, docId) (the author id HTTP edits are attributed to; default 'server'; never taken from the body) | |
type EditOp, parseEdit, runEdit | POST /docs/:id/edit body { ops: EditOp[], version?, confirm? }, ops replaceBlock { id, content }, setBlockAttrs { id, attrs }, insertBlocks { at, content }, deleteBlocks { ids }, replaceDocument { doc }, steps { steps } (raw steps: version required). Authorized as edit before anything is read; all ops apply as one edit or none: 200 { ok, version, steps }, 400 invalid, 404 missing block, 409 stale version, 422 content the schema lacks or a mass delete without confirm, 421 not the owner, 503 not persisted | |
type DocRouteOptions | the document create/list routes' options (also part of RouteOptions): allowCreate? (false: PUT /docs/:id creates a document from a whole snapshot, ?title=, gzip accepted), maxDocumentBytes? (64 MB decompressed), allowList? (true: GET /docs[?after=&limit=], paged (1,000 per page by default, X-Folio-Next = the next page's after), each document still passes authorize(req, id, 'read')) | |
type Authorize | (req, docId, action: Action) => boolean | Promise<boolean> | auth hook; false = 403 |
type Action | 'read' | 'write' | 'create' | 'collab' | 'edit' (edit: server-side edits over HTTP; grant it to trusted services only) | |
class CollabGateway | new (docs, opts?: CollabOptions) | /docs/:id/collab upgrades to a CollabRoom (the document loads on first access; a room keeps it in memory until its last member leaves); every commit (REST pushes included) is broadcast through docs.onCommit; observe(docId); heartbeats; close() |
type CollabOptions | authorize?, maxMessageBytes? (4 MB), heartbeatMs? (30 s), room?(docId) (history, step limits) |
Routes: POST /docs/:id/edit (server-side edits, when allowEdits), GET /docs/:id/manifest[?first=1], GET /docs/:id/chunks/:hash, GET /docs/:id/pages/:n, POST /docs/:id/steps (200 accepted, 409 behind, 422 refused, 503 + Retry-After busy or not persisted), GET /docs/:id/steps?since=N (410: older than the retained history), PUT /docs/:id/layout, PUT /docs/:id (create, when allowCreate), GET /docs[?after=&limit=], GET /health, WebSocket /docs/:id/collab. Every document route authorizes first, then loads the document on demand.
Documents and storage
| Export | Signature | Description |
|---|---|---|
class PersistentDocumentServer | new (schema, storage: DocStorage, opts?: PersistOptions) | MemoryDocumentServer (same validation, chunking, pulls) over a DocStorage. Nothing loads at construction: open(docId) => Promise<boolean> loads on first access (concurrent first accesses share one load; false = not in storage), idle documents leave memory (ResidencyOptions). await submit(...) appends to storage before the push is applied, acknowledged and broadcast; pushes to one document queue behind an append in flight; a failed append refuses the push with nothing changed. push() throws (use submit). await edit(docId, fn, opts?) (server-side edits as steps: see MemoryDocumentServer.edit; loads the document if needed, fenced like pushes). checkpoint(docId, name?) (keep the current document as named version history), storageStats(docId), retention. Also create(docId, doc?, meta?) (async), load(docId) (reload), listPage({ after?, limit? }), retain/release (keep loaded), sweep(), snapshot(docId), close(), lastPersistMs |
type PersistOptions | OwnershipOptions + snapshotEvery (2000 steps), snapshotIdleMs (10 s), retention?: RetentionPolicy; retainSteps / retainStepBytes are deprecated aliases of retention.keepSteps / keepBytes (retention wins) | |
type RetentionPolicy, type Retention, resolveRetention, keepCount | { keepSteps? (20,000), keepBytes? (8 MB), keepDays? (none), checkpointEvery? (0: no periodic checkpoints), keepCheckpoints? (10 periodic; named ones always kept) }: the step history kept in memory and in the log after each snapshot (older pulls get 410 / gone: reopen); resolveRetention(opts) = the effective policy; keepCount(bytes, ats, policy, now) = how many newest steps it keeps | |
type StorageStats, type RawStorageStats, type CheckpointInfo | storageStats(docId): { docId, version, snapshotBytes, logSteps, logBytes, logFrom, oldestVersion, checkpoints: { count, named, bytes, oldest? }, memory: { steps, bytes }, bytesPerStep, growthPer1kEdits, retention }; what DocStorage.stats returns; { version, at, name?, bytes } | |
class LoadingDocumentServer, type LoadingOptions | the lazy-loading base of PersistentDocumentServer (open, load, create, listPage, retain/release, eviction); options: ServerOptions, ResidencyOptions, warmManifests (true: build a document's manifest in the background right after it loads) | |
type ResidencyOptions | evictIdleMs (10 min; Infinity keeps everything), maxLoadedDocs (unlimited; beyond it least recently used idle documents go first). A document never leaves memory while a collab room holds it, writes are pending or steps are unsnapshotted (it is snapshotted first) | |
docWire | (doc: PMNode) => string | compact JSON of a whole document (reuses the per-block wire memo) |
interface DocStorage | list(opts?: ListOptions), load, create(docId, doc, meta?, fence?), append(docId, from, steps, fence?), snapshot(docId, version, json, keepFrom, fence?), claim?(docId, fence) (required with ownership), saveLayout?, checkpoint?(docId, { version, at, name?, docJson }, fence?), checkpoints?(docId), readCheckpoint?(docId, version), dropCheckpoint?(docId, version, fence?), stats?(docId), head? (version + title without loading, for listings), close?; every method returns a value or a Promise (MaybePromise). Contract: append resolves only once durable (the push is acknowledged after it; a rejection refuses it) and refuses a from that isn't the store's next version; snapshots replace the previous one atomically; writes under a stale fencing token throw StaleTokenError. See Collaboration server | |
type ListOptions, type DocHead, pageIds, type MaybePromise | { after?, limit? } (ids ascending); { version, title? }; pageIds(ids, opts) pages a whole id list; T | Promise<T> | |
type StoredDoc | { snapshot: { version, doc }, log: StepEntry[], logFrom, layout?, meta? } | |
type DocMeta | display metadata given at creation ({ title? }), stored on StoredDoc.meta; DocStorage.create(docId, doc, meta?) | |
class MemoryStorage | the contract in memory, synchronous, fenced (tests, demos, several instances in one process) | |
class FileStorage | new (dir, opts?: FileStorageOptions) | asynchronous I/O: snapshot.json (atomic rename, never replaced by an older version) + steps.log (JSON lines, fsynced) + layout.json + meta.json + fence.json (+ the write-once fenced marker) + checkpoints/<version>.json with an index.json per document. Every write and load runs under a per-document lock (in-process queue + withFileLock), and the open log is revalidated under it, so processes on one host never interleave; fencing fails closed (an unreadable, corrupt or vanished token record refuses the write). A torn last line is dropped on load, a corrupt middle line refuses to load. Every document id is validated (isValidDocId) and every path confined to dir by the store itself, whatever the caller checked; checkpoint files are named by integer version only. Single-host: mutual exclusion needs a local filesystem (atomic O_EXCL and rename); instances on several hosts need a database-backed DocStorage |
type FileStorageOptions | fsync (true), compactLogBytes (8 MB) | |
isValidDocId | (id: string) => boolean | letters, digits, ., _, -, up to 128, not only dots |
type AssetRouteOptions | assets?: AssetStorage (off unless given), maxAssetBytes? (50 MB): a document's files at POST /docs/:id/assets (write access; create access before the document exists, so a new deck's pictures go first) → { url, hash, type, size }, and GET /docs/:id/assets/:hash (read access; immutable, Range, nosniff, sandbox CSP) | |
interface AssetStorage, type Asset | put(docId, hash, { type, bytes }), get(docId, hash): content-addressed files | |
class MemoryAssetStorage, class FileAssetStorage | new FileAssetStorage(dir) | in memory; files under dir/<docId>/assets/<hash> (written then renamed) |
sniffMedia, assetHash | (bytes) => string | undefined, (bytes) => string | the media type from a file's bytes (PNG, JPEG, GIF, WebP, BMP, AVIF, MP4, QuickTime, WebM, MP3, M4A, WAV, Ogg, FLAC; never SVG or HTML); the 32-hex content hash |
Ownership (several instances)
Off unless ownership is given. Guide: Collaboration server.
| Export | Signature | Description |
|---|---|---|
type OwnershipOptions | part of PersistOptions: ownership?: DocOwnership, instance?: Instance (default: a fresh id per process, no URL), leaseMs? (30 s; renewed every third of it) | |
class OwnedDocumentServer | the ownership layer PersistentDocumentServer extends: a document loads only on the instance holding its lease (others throw NotOwnerError), storage is claimed with the lease's token before the load, every write carries it; leases, owns(docId), onLost(fn) (the lease is gone: the document was dropped) | |
interface DocOwnership | acquire(docId, me, ttlMs) => AcquireResult, renew(lease, ttlMs) => Lease | null, release(lease); tokens strictly increase whenever a document changes hands and are never reused | |
type Lease, type Instance, type AcquireResult | { docId, owner, hint?, token, expiresAt }; { id, url? } (url is the owner hint); { lease } | { held } | |
class StoreOwnership | new (store: LeaseStore, now?) | the reference DocOwnership over any compare-and-set store (Redis, a SQL row) |
interface LeaseStore | get(docId), swap(docId, expected, next) => boolean (compare-and-set) | |
class MemoryLeaseStore, class MemoryOwnership | new MemoryOwnership(now?) | in process memory: share one between server instances in a process (tests) |
class Leases | this instance's leases: acquire, fence, holds, renewAll, release, releaseAll, lose, onLost, stop | |
type WriteFence, checkFence, class StaleTokenError | checkFence(docId, highest, fence?) => number | the token a write carries; the rule every store applies (refuse a lower token, and unfenced writes once a token was seen); what a store throws then |
class NotOwnerError | another instance owns the document (owner, hint): HTTP 421 Misdirected Request with X-Folio-Owner: <hint> and { error: 'not-owner', owner, hint }, WebSocket upgrade 421 | |
NOT_OWNER_CLOSE | 4409 | WebSocket close code when this instance loses a document's lease (reason {"error":"not-owner"}): clients reconnect, through the load balancer, to the new owner |
withFileLock, type FileLockOptions | (path, fn, { staleMs?, timeoutMs? }) | an exclusive lock file around fn for processes on one host: acquired with O_EXCL holding the holder's id, refreshed while fn runs, broken when stale only under a guard lock after re-checking it is the same file, released only by its holder; a timeout refuses (never runs fn unlocked). Not mutual exclusion on network filesystems |
Validation and HTTP helpers
| Export | Description |
|---|---|
parsePush(body) / type PushBody | shape check of POST /steps (400 on anything else); the steps go through validatePush |
parseLayout(body) | bounded, typed LayoutReport |
class HttpFail | client error with a status, safe to show |
negotiate(req) / type Encoding | 'br' | 'gzip' | 'identity' from Accept-Encoding (honours q=0) |
compress(body, enc) | brotli (quality 5) or gzip on zlib's threadpool |
class CompressedCache | byte-bounded LRU of compressed immutable bodies |
readBody(req, limit) | request body as text, 413 beyond limit |
send(req, res, status, body, opts?: SendOptions) / type SendOptions | JSON response, compressed when accepted and ≥ 1 KB |
Comments
Off unless createFolioServer({ comments: { identify, ... } }). Routes under /docs/:id/comments; every change is also sent to the document's collaborators as a collab event. Guide: Comments plugin.
| Export | Description |
|---|---|
createCommentRoutes(opts) / type CommentRoutesOptions | the routes for any node:http server: identify (required; the author always comes from here), the client's policy options (readers, canEdit...), authorize, backend, exists, onChange, onMention, maxBodyBytes. Writes per document are serialized; 401 anonymous, 403 policy/hook, 404 unknown thread or document |
type CommentAuthorize | (req, docId, action, { user, op?, thread? }) => boolean | Promise<boolean>: an extra check after the policy |
type CommentBackend, MemoryCommentBackend, FileCommentBackend(dir) | where threads persist (<dir>/<docId>.comments.json, written atomically) |
insecureHeaderIdentity(header?) | demo only: trusts a JSON user in X-Folio-User |