Skip to content

Writing a data source

The data source contract is stable in v1: a plugin written against definePlugin (sources, options…), defineClientPlugin, SecretRefSchema / readSecret, PluginSource, PluginSourceContext, PluginSourceResult and DataSourceMeta keeps working across Récit 1.x (full symbol and diagnostic list in Stability). The rest of the plugin API — directives, components, film blocks, themes, exporters, commands, AI jobs, and internal loaders such as findPluginSource — remains experimental (Stability).

Minimal plugin

A data source plugin needs a Node entry (src/index.ts), the lazy module of each source (src/rows.ts), and a browser entry (src/client.ts) without schemas or Node imports so a site can evaluate recit.config.ts in the browser (Writing a plugin):

TypeScriptTypeScript
// src/index.ts import { definePlugin } from "recit/plugin"; import * as z from "zod"; import { readPluginVersion } from "./version.js"; export default definePlugin({ name: "lorem", api: 1, version: readPluginVersion(), options: z.strictObject({ baseUrl: z.url().default("https://api.example.org"), }), sources: { "lorem-rows": () => import("./rows.js"), }, });
TypeScriptTypeScript
// src/rows.ts import type { DataColumnType, DataSourceMeta, PluginSource } from "recit/plugin"; import * as z from "zod"; const EntrySchema = z.strictObject({ dataset: z.string().min(1), limit: z.number().int().min(1).max(1000).default(100), }); const OptionsSchema = z.object({ baseUrl: z.string(), }); const COLUMNS: Record<string, DataColumnType> = { region: "string", visits: "number", }; const loremRows: PluginSource = { schema: EntrySchema, ttl: 3600, async read(context) { const entry = EntrySchema.parse(context.entry); const { baseUrl } = OptionsSchema.parse(context.options); const url = new URL(`/datasets/${encodeURIComponent(entry.dataset)}.json`, baseUrl); url.searchParams.set("limit", String(entry.limit)); const response = await fetch(url, { signal: context.signal }); if (!response.ok) { throw new Error(`lorem-rows: HTTP ${response.status} from ${url}`); } const payload = (await response.json()) as { rows: Array<{ region: string; visits: number }>; modified?: string; }; const meta: DataSourceMeta = { title: "Lorem ipsum visits", publisher: "Lorem Ipsum Institute", license: "CC-BY-4.0", url: url.toString(), ...(payload.modified ? { modified: payload.modified } : {}), }; return { rows: payload.rows, columns: COLUMNS, meta, }; }, }; export default loremRows;
TypeScriptTypeScript
// src/client.ts import { defineClientPlugin } from "recit/plugin"; export default defineClientPlugin({ name: "lorem", });

recit/plugin and @recit/core/plugin export the same definePlugin, defineClientPlugin, PluginSource, PluginSourceContext, PluginSourceResult, DataSourceMeta, DataSourceMetaSchema, DataCell, DataColumnType, SecretRefSchema, SecretRef and readSecret (Stability).

Using the source in a story

Register the plugin in recit.config.ts:

TypeScriptTypeScript
// recit.config.ts import lorem from "recit-plugin-lorem"; import { defineConfig } from "recit/config"; export default defineConfig({ plugins: [lorem()], });

Then declare an entry with source: "lorem-rows" under data: in a story (or in a site page):

MarkdownMarkdown
--- title: Lorem ipsum format: deck data: visits: source: lorem-rows dataset: lorem-quarterly limit: 50 --- --- id=visits # Visits ::chart{data=visits type=bar x=region y=visits}

In the v1 JSON Schema, DataPluginSourceSchema (x-recit-stability: "stable") checks source; at build time, Récit validates the remaining keys (dataset, limit) with the source's schema before calling read.

Context and result

read(context) receives a PluginSourceContext:

FieldTypeMeaning
namestringKey of the table under data: (for example "visits").
entryRecord<string, unknown>Keys of the data: entry without source, validated by schema.
optionsunknownPlugin options passed in recit.config.ts, validated by definePlugin's options schema.
envReadonly<Record<string, string | undefined>>Environment dictionary for readSecret(secret, context.env).
baseDirstringDirectory of the story file.
signalAbortSignal | undefinedOptional in the type so unit tests can call read without a controller; always provided by Récit and aborted when the read timeout (30 s) expires.

read(context) resolves to a PluginSourceResult:

FieldTypeMeaning
rowsRecord<string, DataCell>[]Table rows (string, number, boolean or null cells).
columnsRecord<string, DataColumnType>?Optional column types ("string", "number", "date", "boolean"); inferred from the rows when omitted.
metaDataSourceMeta?Optional dataset provenance using DCAT field names: title, url, publisher, license, modified (ISO date or date-time).

Récit validates and caches meta alongside rows. When an author writes ::chart without a source= attribute, @recit/data composes the Source: caption from publisher, title and license.

Execution rules, cache and diagnostics

Every plugin data source runs in Node at build time and hands inline rows to @recit/data; nothing runs in the browser.

  • 30 s timeout and signal. Each read call is bounded to 30 seconds. When the deadline expires, Récit aborts context.signal and fails the reading (took longer than 30 s). Pass { signal: context.signal } to fetch so in-flight requests stop immediately.
  • 100,000 rows. Returning more than 100,000 rows fails the reading without truncating rows or writing an oversized table to .recit/cache/.
  • Cache and ttl. Valid readings are written to .recit/cache/data/ for ttl seconds (3600 by default; ttl: 0 reads on every build without reading or writing the cache). The cache file key hashes the entry, the plugin's options and version, and the values of any referenced secrets (secret values never appear in the file name).
  • Future timestamps. A cache entry whose readAt timestamp is in the future (readAt > now()) is never treated as fresh: Récit re-reads the source, while keeping that cache file available as a plugin-stale fallback if the fresh read fails.
  • recit build --refresh. Bypasses fresh cache hits and calls read again for every plugin data source.
  • Offline fallback and diagnostics.
    • plugin-stale (warning): read failed (network error, timeout, row limit or invalid rows) and a valid cached reading within the row limit exists on disk — even past ttl, with a future readAt, or under --refresh. Récit serves the cached table and warns with the cache date.
    • plugin-failed (error): read failed and no valid cached reading exists; the build fails.
    • plugin-missing (error): data: names a source that no plugin in recit.config.ts declares.
    • plugin-options-invalid (error): the entry's keys fail the source's schema, or the plugin's options fail options.
    • plugin-no-browser-entry (error): in a site, the plugin package has no browser export (defineClientPlugin).
  • recit validate. On a deck (in Markdown or in its JSON twin) that declares data:, recit validate resolves its plugin sources and reports plugin-failed, plugin-stale and plugin-missing alongside plugin-options-invalid. A project whose plugins declare only fields of the data source contract (name, api, version, options, sources) does not receive a plugin-experimental warning.

Secrets

Never accept a raw token or API key in recit.config.ts or in story front matter, and never read process.env at module import time. Declare every secret with SecretRefSchema ({ env: "NAME" }) and resolve it inside read with readSecret(secret, context.env):

TypeScriptTypeScript
import { type DataCell, type PluginSource, readSecret, SecretRefSchema } from "recit/plugin"; import * as z from "zod"; const EntrySchema = z.strictObject({ dataset: z.string().min(1), token: SecretRefSchema, }); const protectedSource: PluginSource = { schema: EntrySchema, async read(context) { const entry = EntrySchema.parse(context.entry); const token = readSecret(entry.token, context.env); if (!token) { throw new Error(`lorem-rows: environment variable ${entry.token.env} is not set`); } const response = await fetch(`https://api.example.org/datasets/${entry.dataset}`, { headers: { Authorization: `Bearer ${token}` }, signal: context.signal, }); if (!response.ok) { throw new Error(`lorem-rows: HTTP ${response.status}`); } return { rows: (await response.json()) as Array<Record<string, DataCell>> }; }, };

In a story, the author writes token: { env: LOREM_TOKEN }. Only the validated rows and meta reach the rendered page.

Testing without network

Test read directly without touching the network — either by accepting a custom fetch function in the plugin's options, or with vi.stubGlobal("fetch", …) in Vitest:

TypeScriptTypeScript
import { describe, expect, it, vi } from "vitest"; import loremRows from "../rows.js"; describe("lorem-rows", () => { it("parses rows and forwards signal to fetch", async () => { const controller = new AbortController(); const fakeFetch = async (input: string | URL, init?: RequestInit) => { expect(init?.signal).toBe(controller.signal); expect(String(input)).toBe("https://api.example.org/datasets/q1.json?limit=2"); return Response.json({ rows: [{ region: "Lorem", visits: 42 }], modified: "2026-11-01", }); }; // Or stub global fetch with `vi.stubGlobal("fetch", fakeFetch)` vi.stubGlobal("fetch", fakeFetch); try { const result = await loremRows.read({ name: "visits", entry: { dataset: "q1", limit: 2 }, options: { baseUrl: "https://api.example.org" }, env: {}, baseDir: ".", signal: controller.signal, }); expect(result.rows).toEqual([{ region: "Lorem", visits: 42 }]); expect(result.meta?.publisher).toBe("Lorem Ipsum Institute"); } finally { vi.unstubAllGlobals(); } }); });

Passing an optional fetch in options (marked internal in your TypeScript type) works without global stubs and lets tests run concurrently.

Reading the package version at runtime

definePlugin's version is part of the .recit/cache/ key: when a plugin ships a fix to its row normalisation, bumping the package version invalidates cached readings automatically.

Do not read "version" with a static import pkg from "../package.json": bundlers inline that value at build time, before a release step bumps package.json. Resolve and read package.json at runtime instead:

TypeScriptTypeScript
// src/version.ts import { readFileSync } from "node:fs"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; const resolveManifestPath = (): string => { try { return createRequire(import.meta.url).resolve("recit-plugin-lorem/package.json"); } catch { return fileURLToPath(new URL("../package.json", import.meta.url)); } }; export const readPluginVersion = (): string => { try { const parsed = JSON.parse(readFileSync(resolveManifestPath(), "utf8")) as { version?: unknown; }; return typeof parsed.version === "string" && parsed.version.trim() !== "" ? parsed.version.trim() : "0.0.0"; } catch { return "0.0.0"; } };

Real-world example

@recit/source-datagouv implements the v1 data source contract for French public open data on data.gouv.fr (source: "datagouv", ttl: 86_400, no token): it fetches data/json/ and profile/ column types from tabular-api.data.gouv.fr (downgrading mixed columns to "string"), falls back to raw CSV via the catalogue API (www.data.gouv.fr/api/) on HTTP 404, populates DCAT meta (title, publisher, license, modified, url), reads its package.json version at runtime, accepts an injectable fetch in options for offline unit tests, and ships a zero-schema browser entry.