@ogygia/content
Collections
Define a set of typed entries once, from markdown files, JSON, a CMS or a live feed, and read it the same way whatever the source. Entries are checked by your schema, linked to each other, and filtered once for every read; a body renders as a region with its islands awake.
On this page
- Collection definition
- Schemas
- Layer several schemas
- Filters
- Reading entries
- Entries in pages
- Prerender every entry
- Render it in the same server pass
- Lists in the browser
- Render a body the browser fetched
- Relations
- Entry ids
- Custom sources
- Parse files no loader reads
- Add derived facts to meta
- Live sources
- Watch a server push
- Dev reloading
- Do and don’t
See it all live
Playground ↗ is a second site, built inside this one, that uses this page’s features: four markdown corpora, an OpenAPI reference rendered from JSON data, a dated blog, a version × locale switcher, and search. Each of them is a content() collection.
Most of what a site publishes is writing: docs, blog posts, changelogs, product pages, entries in a CMS. You usually want two things from it. You want an index the page can list, and you want each entry’s body rendered on its own page, ideally with interactive islands inside it.
A collection gives you both. You call content({ loader, schema }) once. The loader says where entries come from (a folder of markdown, JSON files, a CMS, a feed that pushes changes), the schema checks each entry’s frontmatter, and you read the result with the same two calls whatever the source: refs() lists the entries, get(id) reads one with its body.
What you get back depends on where you read it. On the server you get the whole entry, body included. What crosses to the browser is plain data, or a body that has been rendered to HTML first:
| Read | Returns | Where |
|---|---|---|
refs() | every visible entry’s id, data and meta (with rel and backlinks when linked), no bodies | server |
get(id) | one entry: id, data, meta, body, rel, backlinks | server |
withRemotes(c).list({ map }) | your mapped data for every entry, as a Kit remote | over the wire |
withRemotes(c).live.list / .get | the same, sent again whenever the source changes | over the wire (live) |
A page assembled from typed blocks rather than one markdown body is the same kind of collection with a different source: see Blocks. To arrange collections into a site with a sidebar, search and prev/next, see Site.
import { content } from '@ogygia/content';
import * as v from 'valibot';
export const posts = content({
loader: import.meta.og.loader.markdown('../content/posts'),
schema: v.object({ title: v.string(), date: v.string() })
});Collection definition
A collection’s loader holds the whole compiled corpus, which can be megabytes of markdown. So define the collection in a module the browser can never import: a .server.ts file or a file under src/lib/server/. Kit refuses any client import of those, so the corpus can’t end up in a browser bundle. A .remote.ts works too, as a const you don’t export: Kit gives the browser fetch stubs in place of that file, and it requires every export of it to be a remote function.
content() takes four options:
loader(required) is the source. For files in your repo, use a loader macro:import.meta.og.loader.markdown,.folder,.jsonor.git. For anything else, write a source of your own.schemachecks and types each entry’s frontmatter. See Check frontmatter with a schema.filterhides entries from every read. See Hide entries with a filter.relationslinks entries to entries in other collections, or the same one. See Link entries to each other.
The types come from the options: data is your schema’s output and meta is whatever the source adds (headings and links, for markdown), so you write no annotations. The exception today is that loader.folder and loader.git type meta as empty, even though their markdown entries carry headings and links. Pass the type to read them: import.meta.og.loader.folder<MarkdownMeta>('../content/docs'), with MarkdownMeta imported from @ogygia/content.
Two checks guard the server-only rule. Defining a collection, or calling a loader macro, in any other module of your app prints content_collection_not_server_only when the module is compiled (dev or build), once per file. And after a client build, if a compiled .svx or .md file turns up in a browser chunk, the build prints content_leaked_to_client with the first five files and the chunk that holds them. Both are warnings; neither fails the build.
A content() call without a loader throws content_loader_missing, and a loader that isn’t an object with refs() and get() throws content_loader_not_source.
import { content } from '@ogygia/content';
import * as v from 'valibot';
export const docs = content({
loader: import.meta.og.loader.folder('../content/docs'),
schema: v.object({
title: v.string(),
draft: v.optional(v.boolean(), false)
}),
filter: (e) => !e.data.draft
});Schemas
schema validates each entry’s data (a markdown file’s frontmatter, a JSON file’s object, a CMS row). It takes any Standard Schema, so valibot, zod and arktype all work, or any object with a parse(value) method that returns the value or throws. The validated output is what data holds, so defaults and transforms in the schema apply.
An entry that fails throws content_schema_failed, naming the entry (content/<id>) and the schema’s messages. The first read of a collection is strict: one bad entry fails that read, which fails a prerender or a build. A schema that is neither a Standard Schema nor has parse throws content_schema_unsupported.
Layer several schemas
schema can also be an array. Each schema in it checks the original data, and their outputs merge from left to right, a later key winning. So a shared base schema can sit beside the fields one collection adds, and neither drops the other’s keys. The type of data is every layer’s output combined.
fields from @ogygia/content holds three ready-made layers for site pages, with no validation library behind them:
| Layer | Keeps |
|---|---|
fields.page | title (required, not empty), summary (default ''), draft (default false), badge, redirect_from, related (default []) |
fields.post | fields.page, plus date (required), author and tags (default []) |
fields.change | fields.page, plus version and date (both required) |
fields.page drops every key it doesn’t list, so add a layer of your own for anything else.
fields.page is one schema, but fields.post and fields.change are already arrays of two. So list the page layer as [fields.page, extra] and spread the others: [...fields.post, extra]. version must be text, so quote it in YAML (version: '1.2'); a bare 1.2 is a number and fails the check.
import { content, fields } from '@ogygia/content';
import * as v from 'valibot';
export const blog = content({
loader: import.meta.og.loader.markdown('../content/blog'),
schema: [
...fields.post,
v.object({ cover: v.optional(v.string()) })
]
});Filters
filter(entry, ctx) decides which entries exist. It runs on every read: refs(), get(), the wire remotes, the relations, and the prerender entries a site lists. A draft it hides is gone everywhere, including at its own URL, where get() answers null.
The second argument is a read context, a plain object you pass to a read: refs(ctx) or get(id, ctx). With none, it’s {}, the public view. Use it for previews and roles. A site derives it from each request with its context option.
A remote can add a filter of its own (see Send a list to the browser). It only narrows what the collection’s filter allows; it can never show an entry the collection hides. The withRemotes remotes always read the public view, with {} as the context, so a draft that only { preview: true } shows never appears in list, live.list or live.get. For previews, read with get(id, ctx) in a load or a remote of your own.
import { content } from '@ogygia/content';
import * as v from 'valibot';
export const docs = content({
loader: import.meta.og.loader.folder('../content/docs'),
schema: v.object({
title: v.string(),
draft: v.optional(v.boolean(), false)
}),
filter: (e, ctx) => !e.data.draft || ctx.preview === true
});
// await docs.get('roadmap') → null while it's a draft
// await docs.get('roadmap', { preview: true }) → the entryReading entries
get(id, ctx?) returns one entry, or null when the id is unknown or filtered out. It never throws for a missing entry, so you decide where a 404 happens, usually in a load:
id: the entry’s id. For files, it’s the path below the folder without the extension (see How entry ids are made).data: the validated frontmatter.meta: what the source works out. Markdown fillsmeta.headings(theh2toh4headings, as{ depth, id, text }) andmeta.links(every markdown link, which the link check reads). Other sources give{}unless you add your own.body: the rendered page as a held region. Render it with<Region of={entry.body} />. JSON entries have none.source: for markdown, a function that returns the file’s raw text. It loads only when you call it.relandbacklinks: the linked entries (see Link entries to each other);{}and[]when there are none.
refs(ctx?) returns every visible entry without bodies: id, data, meta, plus order and filePath when the source has them, and rel and backlinks when the collection is linked to another. Use it for indexes and prerender lists. groups() returns the section labels a folder source reads from +meta.json files, as a Map from the section’s path to { label }.
A collection without relations reads only the one entry get() asks for. A collection that has relations, or that another collection points to, reads all its entries on the first get(), because a backlink can come from any of them.
import { error } from '@sveltejs/kit';
import { docs } from '$lib/docs.server';
export const load = async ({ params }) => {
if (!(await docs.get(params.slug))) error(404, 'Not found');
};Entries in pages
A page component can’t import a server module, so it reads the entry through a remote function. The body has to cross the wire, and a raw body can’t: it’s a component waiting to render. Await it first. await entry.body renders the body to HTML on the server and turns it into a small ticket that carries that HTML. The page swaps it in with no extra fetch, and any islands inside the body wake as usual.
A body returned without await fails with held_region_plain_import when Kit sends it.
Remote functions need Kit’s kit.experimental.remoteFunctions, await in a component needs Svelte’s compilerOptions.experimental.async, and a region crossing from a remote needs ogygia’s transport hook in src/hooks.ts.
Prerender every entry
To prerender each entry, list the ids from refs() as the route’s entries. A site does this for you with its entries (export const { entries } = site).
Render it in the same server pass
On a csr = false page, a universal +page.ts load and the page component run only on the server. They can call get() and hand entry.body straight to <Region>: the body renders as part of the page, with no remote and no await. It’s limited by the import. Kit doesn’t let universal code import a server-only module, so the collection has to live in an ordinary module, and ogygia prints content_collection_not_server_only for it. That’s a fair trade for a small collection with no compiled corpus, such as a blocks page. For markdown, keep the remote.
import { query } from '$app/server';
import * as v from 'valibot';
import { docs } from './docs.server';
export const entry = query(v.string(), async (slug) => {
const e = await docs.get(slug);
if (!e) return null;
return {
data: e.data,
body: e.body ? await e.body : undefined
};
});<script lang="ts">
import { page } from '$app/state';
import { Region } from 'ogygia';
import { entry } from '$lib/docs.remote';
const view = (await entry(page.params.slug ?? ''))!;
</script>
<h1>{view.data.title}</h1>
{#if view.body}<Region of={view.body} />{/if}import { docs } from '$lib/docs.server';
export const prerender = true;
export const entries = async () =>
(await docs.refs()).map((e) => ({ slug: e.id }));Lists in the browser
withRemotes(collection) from @ogygia/content/server makes Kit remote functions over a collection. It imports $app/server, so call it in a .remote.ts, where Kit requires every export to be a remote. Given anything other than a content() handle, it throws content_with_remotes_not_collection.
list(options?) makes a remote that returns every visible entry, mapped:
| Option | Default | What it does |
|---|---|---|
map | (e) => ({ id: e.id, data: e.data }) | Turns each entry (id, data, meta, rel, backlinks) into what crosses. Send only what you need. |
filter | none | Narrows the collection’s own filter, which runs with the public context {}. |
mode | 'prerender', or 'query' for a live source | 'prerender' makes a Kit prerender remote, 'query' a query that reads on each request. |
dynamic | true | Passed to Kit’s prerender: true lets it also answer at runtime for anything not prerendered. |
A source you write yourself reads at request time, but list() still defaults to 'prerender' for it; pass mode: 'query' when the list must be fresh per request. A live source can’t be prerendered: mode: 'prerender' on one throws content_streaming_prerender_list.
withRemotes takes the data type as a type argument (withRemotes<Post>(posts)). It accepts any value and checks it at runtime, so it can’t infer the type from the collection, and without the argument data is Record<string, unknown>.
Render a body the browser fetched
list sends data, not bodies. When the browser has to render something it fetched (a search result, an item in a feed), map the entry to a held region of one of your own components, imported with { region: 'raw' } or with a wake mark, and return that. <Region> fetches and renders it. Held regions explains the marks.
import { withRemotes } from '@ogygia/content/server';
import { docs } from './docs.server';
export const docNav = withRemotes<{ title: string }>(docs).list(
{
map: (e) => ({ slug: e.id, title: e.data.title })
}
);<script lang="ts">
import { docNav } from '$lib/docs.remote';
const nav = await docNav();
</script>
<ul>
{#each nav as item}<li>
<a href="/docs/{item.slug}">{item.title}</a>
</li>{/each}
</ul>Relations
relations declares which frontmatter fields point at other entries. It’s a function that gets the collection’s own handle, so a collection can point at itself without naming the const it’s being assigned to. It returns an object: each key is a frontmatter field, each value the collection that field’s ids belong to.
The field holds one id (a string) or several (an array of strings). On every read, rel holds the matching entries as { id, data }:
- one id: the entry, or
nullwhen it doesn’t exist or is filtered out; - an array: the entries that exist, in order.
backlinks goes the other way: every entry, in any collection, whose relation field names this one. Both are shallow (id and data, no body), so build a link from ref.id, or get(ref.id) for more.
rel is typed as a record of RefEntry | RefEntry[] | null, so give it the target’s data type where you read it.
import { content } from '@ogygia/content';
import * as v from 'valibot';
export const people = content({
loader: import.meta.og.loader.json('../content/people'),
schema: v.object({ name: v.string() })
});
export const posts = content({
loader: import.meta.og.loader.markdown('../content/posts'),
schema: v.object({
title: v.string(),
author: v.string(),
related: v.optional(v.array(v.string()), [])
}),
relations: (self) => ({ author: people, related: self })
});import { error } from '@sveltejs/kit';
import type { RefEntry } from '@ogygia/content';
import { posts } from '$lib/collections.server';
export const load = async ({ params }) => {
const post = await posts.get(params.slug);
if (!post) error(404, 'Not found');
const author = post.rel.author as RefEntry<{
name: string;
}> | null;
return {
title: post.data.title,
author: author?.data.name ?? 'Unknown'
};
};Entry ids
An entry’s id is its address within the collection, and usually part of its URL. The file loaders make it from the file’s path:
- the folder every matched file shares is taken off the front, and so is one extension:
../content/posts/2026/hello.svxbecomes2026/hellowhen other posts sit outside2026/, andhellowhen every post is under it; - a folder source also drops each segment’s
NN-ordering prefix and the+doc.svxfile name:03-routing/01-basics/+doc.svxbecomesrouting/basics.
To choose ids yourself, pass id: (key) => string in the loader’s options. key is the file’s path as Vite’s glob gives it, relative to the module.
An id that is empty, contains .. or starts with / throws content_glob_illegal_id. Two files with one id (intro.md beside intro.svx) throw content_glob_duplicate_id. A source you write must give every entry a string id (content_ref_missing_id), each once (content_duplicate_id).
import { content } from '@ogygia/content';
// '../content/posts/2026/hello.svx' → 'hello'
export const posts = content({
loader: import.meta.og.loader.markdown('../content/posts', {
id: (key) =>
key
.split('/')
.pop()!
.replace(/\.(svx|md)$/, '')
})
});Custom sources
A loader doesn’t have to be files. Anything with refs() and get(id) is a source, so a REST API, a CMS or a database works with the same collection and everything on this page applies to it: the schema, the filter, relations and the remotes.
| Method | Required | What it does |
|---|---|---|
refs() | yes | Lists every entry as { id, data, meta?, order?, filePath? }. Never a body: lists, navs and indexes read this. |
get(id) | yes | Reads one entry: the same fields plus an optional body (a region) and source. null when it doesn’t exist. |
init() | no | Runs once before the first read. Load heavy dependencies here. |
live() | no | Returns an async iterable that yields when the source changes. See Follow a live source. |
groups() | no | Returns section labels as a Map of path to { label }. |
get(id) should fetch one entry, not the whole list: a page pays only for what it shows.
A CMS row gives you data, not a compiled body. Render it through a component of your own, as a held region (see Render a body the browser fetched), or with a blocks source if the CMS sends a tree of components.
Parse files no loader reads
There’s no loader for YAML or plain-text files. Build one in a few lines with the same pieces the built-in loaders use:
toRawSource(input, { id }?)turns animport.meta.globmap into a raw source of unparsed values, with ids made as above. An object that already hasrefsandgetis passed through unchanged and treated as raw ({ id, value }records).defineSource(raw, format, extra?)applies a format,(value, id) => ({ data, meta?, body?, source? }), to each raw value.extracan add aninitandgroups.mapRaw(raw, fn)changes every raw value before the format sees it, for example to reshape a CMS’s JSON.glob(map, { id }?)is the glob half oftoRawSourceon its own.
Add derived facts to meta
enrich(source, fn) adds facts to every entry’s meta, on refs() and get() alike. fn gets the entry (id, data, meta, filePath) and returns an object that is merged over its meta; it may be async. It works over any source, so a fact like an edit link or a word count is written once for files and a CMS. The type of meta grows with what fn returns.
import { content } from '@ogygia/content';
import * as v from 'valibot';
const API = 'https://cms.example.com/api/posts';
export const press = content({
schema: v.object({ title: v.string(), date: v.string() }),
loader: {
async refs() {
const rows: {
slug: string;
title: string;
date: string;
}[] = await fetch(API).then((r) => r.json());
return rows.map((r) => ({ id: r.slug, data: r }));
},
async get(id) {
const res = await fetch(
`${API}/${encodeURIComponent(id)}`
);
return res.ok ? { id, data: await res.json() } : null;
}
}
});import {
content,
defineSource,
toRawSource
} from '@ogygia/content';
import { parse } from 'yaml';
import * as v from 'valibot';
export const team = content({
schema: v.object({ name: v.string(), role: v.string() }),
loader: defineSource(
toRawSource<string>(
import.meta.glob('../content/team/*.yaml', {
query: '?raw',
import: 'default',
eager: true
})
),
(raw) => ({ data: parse(raw) as Record<string, unknown> })
)
});import { content, enrich } from '@ogygia/content';
export const posts = content({
loader: enrich(
import.meta.og.loader.markdown('../content/posts'),
(ref) => ({
editUrl: `https://example.com/edit/${ref.id}`,
sections:
ref.meta?.headings.filter((h) => h.depth === 2)
.length ?? 0
})
)
});Live sources
A source with live() pushes changes. live() returns an async iterable (an async *live() method is the easy way), and each value it yields tells the collection what changed:
- anything (
yield 1): read the whole source again; - an array of ids (
yield ['a', 'b']): read only those, withget(id). An idgetno longer finds is removed. This is the better choice for a large source.
Pair it with withRemotes(c).live.list({ map, filter }) or live.get({ map, filter, notFound }). Both make Kit query.live remotes that send a fresh mapped value every time the collection changes. live.get takes the id as its argument and answers notFound (default null) for a missing or hidden entry. A page reads them like any query.live remote.
The collection subscribes on its first full read (refs(), a remote, or a read that resolves relations), before it reads the source, so a change made during that read isn’t missed. When something goes wrong, it keeps going:
- An entry that fails its schema during a live update keeps its last good version (a new one stays out), the rest update, and
content_live_change_failedis logged. - When
live()throws, the connection has dropped:content_live_source_failedis logged, and the collection subscribes again after 1 second, then 2, 4 and so on up to a minute, with up to a fifth taken off each wait at random. It reads the whole source again each time, so nothing changed meanwhile is lost. It never gives up while the app runs. - When the iterable ends, the collection stops following and keeps what it has.
Watch a server push
In the demo below, a query.live remote, the same kind live.list makes, yields a rendered held region every second. The server renders each one and pushes the HTML, and the page morphs it in place, with no data code in the browser and no fetch per tick.
A live source needs a server that stays up. On short-lived serverless functions each instance has its own subscription and its own copy of the entries, and an instance that stops takes them with it.
import { content } from '@ogygia/content';
import * as v from 'valibot';
import { cms } from '$lib/server/cms'; // your CMS client
export const press = content({
schema: v.object({ title: v.string() }),
loader: {
async refs() {
return (await cms.list()).map((row) => ({
id: row.slug,
data: row
}));
},
async get(id) {
const row = await cms.get(id);
return row ? { id, data: row } : null;
},
async *live() {
for await (const event of cms.changes()) yield event.ids; // only these ids are read again
}
}
});import { withRemotes } from '@ogygia/content/server';
import { press } from './press.server';
export const headlines = withRemotes(press).live.list({
map: (e) => ({ id: e.id, title: e.data.title })
});Dev reloading
On the dev server, editing a file under src/content (or any .remote.ts) invalidates the modules that read it and every loaded .remote.ts, then reloads the page, so lists and bodies are read again. A collection whose module runs again is replaced: the old one closes its live subscription. For content kept outside src/content, add the folder with the plugin’s watchDirs option; see the content() plugin.
Do and don’t
- Do define each collection once, in a server-only module, and read it from loads and
.remote.tsfiles. - Do answer a missing entry with
error(404)in aload;get()returnsnulland leaves the choice to you. - Do
await entry.bodybefore a body leaves the server. - Do map entries down to what the browser needs in
list({ map }), rather than sending all ofdata. - Don’t import a collection into an island or a page component. It pulls the corpus into the bundle, and the build warns.
- Don’t expect a compiled body from a CMS row; render its data through a component.
- Don’t rely on a live source on short-lived serverless functions.