Skip to content

Content

@hamur/content turns folders of Markdown, YAML, JSON, TOML and CSV files into collections you query from a page, a handler or the browser. A collection can have a schema that checks every file at build, a page collection renders to HTML with your UI library's components, and the module adds navigation, search, REST and GraphQL on top. It has no dependency, and the store and the query engine are plain JSON and plain ESM, so it runs on every preset, in the browser and on Workers.

This page covers the module. Markdown itself, with MDC components and highlighting, is in Markdown; every export is in the @hamur/content reference. This documentation runs on @hamur/content: its docs collection has a loader of its own that reads content/ and expands the @include lines.

sh
bun add @hamur/content

Set it up

List the module, then describe the collections in content.config.ts at the app root:

ts
import { defineConfig } from "hamur"
import content from "@hamur/content"

export default defineConfig({ framework: "react", modules: [content] })
ts
import { defineCollection, defineContentConfig, image } from "@hamur/content"
import { array, object, optional, string } from "./schema.ts"

export default defineContentConfig({
  collections: {
    blog: defineCollection({
      type: "page",
      source: "blog/**/*.md",
      schema: object({ date: string(), tags: optional(array(string())), cover: optional(image()) }),
      order: ["date", "DESC"],
    }),
    authors: defineCollection({
      type: "data",
      source: "authors/*.yml",
      expose: false,
      schema: object({ name: string() }),
    }),
    docs: defineCollection({
      type: "page",
      source: {
        repository: "https://github.com/example/docs",
        branch: "main",
        include: "guides/**/*.md",
        prefix: "/docs",
      },
    }),
  },
})

content.config.ts is code: schemas, loaders and transformers. The content key of hamur.config.ts is data, listed below. Without the file the build fails with @hamur/content needs content.config.ts in <rootDir>. hamur dev does not watch content.config.ts; restart it after a change.

A collection name matches [a-z][A-Za-z0-9]*, since it is a TypeScript key, a URL segment and a GraphQL type name (content.config.ts: collection name "my-blog" must match [a-z][A-Za-z0-9]*).

FieldDefaultMeaning
typerequired"page": entries with a path and a Markdown body. "data": entries of fields only
sourcefiles under content/; exactly one of source and loader
loadera loader
schemanoneany Standard Schema; checks each entry at build
exposetruefalse keeps the collection on the server: no client chunk, no query endpoint, no REST or GraphQL
ordersource order[field, "ASC" | "DESC"], the default order of queries

The content key

ts
import { defineConfig } from "hamur"
import content from "@hamur/content"

export default defineConfig({
  framework: "html",
  modules: [content],
  site: { url: "https://example.com" },
  content: {
    clientQuery: "local",
    chunkSize: 500,
    csv: { delimiter: ";", header: true },
    search: { collections: ["docs"] },
    prerender: true,
    raw: true,
    llms: {
      title: "Example docs",
      description: "Guides for Example.",
      sections: [{ title: "Guides", collection: "docs", where: { field: "navigation", operator: "<>", value: false } }],
    },
    api: { rest: true, graphql: false },
  },
})
KeyDefaultMeaning
clientQuery"api"; "local" on statichow queryCollection runs in the browser: "api" posts to /_hamur/content/query, "local" downloads the collection once and runs the engine there. "api" on static fails: content.clientQuery "api" needs a server; the static preset uses "local"
chunkSize1000entries per chunk of a collection in the server bundle; a positive integer
csv{ delimiter: ",", header: true }how .csv files are read
searchfalse{ collections: string[] }: the page collections that get a search index
prerendertrue on static, else falseadds every page path to the prerender routes
rawfalseserves each page's source at <path>.md: true the file on disk, "body" what the loader made of it
llmsnonewrites /llms.txt and /llms-full.txt
api{ rest: false, graphql: false }the REST and GraphQL surfaces

A wrong value fails the build and names the key, for example content.chunkSize must be a positive integer (got 0) or content.raw must be a boolean or "body" (got "yes").

Sources and paths

source is a glob relative to content/, or { include, exclude?, prefix?, cwd? }, or an array of these. cwd moves the base below content/, and prefix (default /) starts the path of every page. A source is the glob loader with these options.

  • Path. prefix plus the file's path, each segment without a leading number (1.), the extension removed and a last segment index dropped: content/blog/1.hello.md is /blog/hello, content/blog/index.md is /blog. A frontmatter path starting with / replaces it. Two entries of one collection with one path fail the build: content: content/blog/hello.md and content/blog/1.hello.md both have path /blog/hello.
  • Order. Segment by segment, by number prefix numerically (a segment with one comes before one without), then by name, so 2.b comes before 10.a. Queries without order, navigation and surroundings use it.
  • Drafts. A page with draft: true in its frontmatter is in the collection under hamur dev and left out of every build, which logs [content] blog: 2 drafts left out.

An entry has these fields; a schema's output adds the rest.

FieldPageDataValue
collection, id, stem, extensionyesyesthe collection's name; the stem (blog/1.hello), or <stem>/<index> for an item of an array file; the stem; "md", "yml", …
pathyesas above
title, descriptionyesfrontmatter, else the first h1 and the first paragraph
seoyes{ title, description } merged with frontmatter seo
navigationyesfrontmatter navigation: true, false or { title?, icon? }
draftyesfrontmatter draft, false by default
bodyyesthe Markdown AST
excerpt, headings, toc, readingTimeyesfrom the Markdown document

A frontmatter or data field named collection, id, stem, extension, body, excerpt, headings or toc fails: content/blog/a.md: frontmatter field "body" is reserved.

Schemas

schema is any Standard Schema: valibot, zod and arktype all are. The build validates each page's frontmatter or each data entry with it, and its output replaces the input. The output must be JSON, so a Date is stored as its ISO string and typed string. The samples here use a small hand-written schema, so they need no library:

ts
import type { StandardSchemaV1 } from "hamur/server"

type Schema<T> = StandardSchemaV1<unknown, T>

const make = <T>(
  validate: (value: unknown) => StandardSchemaV1.Result<T> | Promise<StandardSchemaV1.Result<T>>,
): Schema<T> => ({ "~standard": { version: 1, vendor: "docs", validate } })

const under = (key: PropertyKey, issues: ReadonlyArray<StandardSchemaV1.Issue>): StandardSchemaV1.Issue[] =>
  issues.map((issue) => ({ ...issue, path: [key, ...(issue.path ?? [])] }))

export const string = (): Schema<string> =>
  make<string>((value) => (typeof value === "string" ? { value } : { issues: [{ message: "Expected string" }] }))

export const optional = <T>(schema: Schema<T>): Schema<T | undefined> =>
  make<T | undefined>((value) => (value === undefined ? { value } : schema["~standard"].validate(value)))

export const array = <T>(item: Schema<T>): Schema<T[]> =>
  make<T[]>(async (value) => {
    if (!Array.isArray(value)) return { issues: [{ message: "Expected array" }] }
    const output: T[] = []
    for (const [index, entry] of value.entries()) {
      const result = await item["~standard"].validate(entry)
      if (result.issues) return { issues: under(index, result.issues) }
      output.push(result.value)
    }
    return { value: output }
  })

type Shape = Record<string, Schema<any>>

export const object = <S extends Shape>(shape: S): Schema<{ [K in keyof S]: StandardSchemaV1.InferOutput<S[K]> }> =>
  make<{ [K in keyof S]: StandardSchemaV1.InferOutput<S[K]> }>(async (value) => {
    if (typeof value !== "object" || value === null) return { issues: [{ message: "Expected object" }] }
    const output: Record<string, unknown> = { ...value }
    const issues: StandardSchemaV1.Issue[] = []
    for (const [key, schema] of Object.entries(shape)) {
      const result = await schema["~standard"].validate((value as Record<string, unknown>)[key])
      if (result.issues) issues.push(...under(key, result.issues))
      else output[key] = result.value
    }
    return issues.length > 0 ? { issues } : { value: output as { [K in keyof S]: StandardSchemaV1.InferOutput<S[K]> } }
  })

A failure is one line per issue, with the file and the field: content/blog/a.md: date: Expected string. A loader's entry says content: loader "cms", entry "x": date: Expected string.

image() is a schema for an image field. A relative path in frontmatter or data, relative to the entry's file, becomes { src, width, height, format }: the file is copied with a hash in its name below the build assets, and the size is read from its header. The output is an ImageMeta, so getImage(entry.cover) and <Img src={entry.cover}> of @hamur/image take it. A URL or an absolute path fails with cover: https://… is not a relative path; image() reads files next to the entry, a missing file with content/blog/x.md: cover: ./a.png not found. An entry that comes from a loader with no file fails, since there is nothing to resolve against.

fromComponent<typeof import("./app/components/Hero.ts")>("#app/components/Hero") makes a component's props the schema of a collection. The build imports the component and reads its propsSchema export, a Standard Schema, so a data collection of hero entries is checked as the props of Hero. A React, Preact or Solid component exports propsSchema beside it; a .vue or .svelte component, which the build cannot import without its compiler, keeps it in a sibling Hero.props.ts. A component without the export fails with fromComponent: #app/components/Hero exports no propsSchema. A live collection cannot use it.

Data formats

ExtensionParsed byEntries
.mdparseMarkdownone; a data collection keeps the frontmatter and drops the body
.yml, .yamlBun.YAMLone; in a data collection an array file gives one entry per item
.jsonJSON.parseas YAML
.json5Bun.JSON5as YAML
.tomlBun.TOMLone, an object
.csvHamur's RFC 4180 parserone per row

A page collection reads a YAML, JSON or TOML object as the frontmatter of an empty body; an array file there fails with a page collection entry is one document; move the file to a data collection. In a data collection an item's id is its id field when it has one, else its index; an object file gives one entry per key. CSV values are all strings, so the schema coerces them. With header: false the columns are named "0", "1", and a row with a different number of fields fails with the line and column: content/data/a.csv:3:1: row has 1 field, the header has 2. Any other extension fails: content/blog/a.txt: .txt is not a content format (md, yml, yaml, json, json5, toml, csv), unless a transformer reads it.

Loaders

A loader fills a collection. glob and file ship; a custom loader is an object with a name and a load function.

  • glob({ pattern, base?, exclude?, prefix? }) is what a source is.
  • file(path) reads one JSON or YAML file below content/: an array gives one entry per item, an object one entry per key.
  • A custom loader calls store.set({ id, data, body?, file?, digest?, path? }). With a digest equal to the last build's, the entry is not parsed again. meta keeps strings between builds, such as a sync token. parseData validates through the schema.
ts
import { defineCollection, defineContentConfig, type ContentLoader } from "@hamur/content"

interface Release {
  id: string
  name: string
  notes: string
}

const releases: ContentLoader = {
  name: "releases",
  async load({ store, meta, digest }) {
    const items = (await (await fetch("https://api.example.com/releases")).json()) as Release[]
    for (const key of store.keys()) if (!items.some((item) => item.id === key)) store.delete(key)
    for (const item of items) {
      store.set({
        id: item.id,
        path: `/releases/${item.id}`,
        data: { name: item.name },
        body: `# ${item.name}\n\n${item.notes}`,
        digest: digest(item.notes),
      })
    }
    meta.set("fetched", new Date().toISOString())
  },
}

export default defineContentConfig({
  collections: { releases: defineCollection({ type: "page", loader: releases }) },
})

A loader runs at build and in hamur dev (at start and when a file changes), never at run time. Data that must be fresh at each request is a live collection. An error a loader throws becomes content: loader "releases" failed: <message>.

A remote Git source

A source with repository downloads the tarball of a GitHub or GitLab repository at build, with its include, exclude and prefix relative to the repository's root. Set branch or tag, not both. The files are unpacked with Bun.Archive and cached under the build's cache directory; a build whose fetch fails, with a 5xx, a 429 or no network, uses the cache and logs [content] using the cached copy of https://github.com/org/docs. A 404 fails even with a cache.

DetailBehaviour
hostsgithub.com and gitlab.com over HTTPS; no self-hosted GitLab. Any other: content: https://gitea.example/x is not a GitHub or GitLab repository URL
auth: { token }sent as Authorization: Bearer (GitHub) or PRIVATE-TOKEN (GitLab); never logged, cached or put in an error
limits100 MB downloaded, 500 MB unpacked; an entry that leaves the repository (../x.md) fails the build
hamur devread at start and when another change rebuilds the collection; not watched

Transformers and hooks

defineContentConfig({ collections, transformers }) takes transformers. One with parse reads files of its extensions into entry fields (a string body field of the result is the Markdown a page collection parses). transform runs on every entry after the schema, in list order, and returns the entry.

ts
import { defineCollection, defineContentConfig, defineTransformer } from "@hamur/content"

const text = defineTransformer({
  name: "text",
  extensions: [".txt"],
  parse: (file) => ({ title: file.id, body: `# ${file.id}\n\n${file.body}` }),
  transform: (entry) => ({ ...entry, kind: "note" }),
})

export default defineContentConfig({
  collections: { notes: defineCollection({ type: "page", source: "notes/*.txt" }) },
  transformers: [text],
})

The build hooks content:file:beforeParse({ file, collection }) and content:file:afterParse({ file, entry, collection }) are hooks of hamur.config.ts or a module. The first may assign file.body, the second changes entry in place. The content index's digest covers the transformers' source, so editing one parses every entry again. It does not cover what a transformer imports or a hook's code: delete .hamur/content after changing those.

The content index and chunks

.hamur/content/<collection>.json is the content index: every entry with a digest of its source, the loader's meta, and the digest of content.config.ts, the markdown key and site.url. A build parses only the entries whose digest changed. A schema you import from another file is not in the digest; delete .hamur/content after changing it.

The build writes each collection into the server bundle as JSON chunks of chunkSize entries. The server imports a collection's chunks together on its first query in a process, and a query of one collection imports no other. On a preset that bundles into one module, such as Cloudflare Workers, the chunks are in that module and the answer is the same, but the bytes are not lazy. With clientQuery: "local", an exposed collection is one lazy chunk the browser fetches once. The query engine still reads the whole collection, so a site that outgrows memory is a case for a database-backed engine, which v1 does not have.

Render an entry

renderEntry(entry) from @hamur/content/render returns { html, headings, ast } for a page entry, with no UI library; a Markdown component renders as its tag. A data entry throws renderEntry needs a page collection entry (got data collection "authors").

ts
import { queryCollection } from "@hamur/content/query"
import { renderEntry } from "@hamur/content/render"

export async function postHtml(path: string): Promise<string | undefined> {
  const entry = await queryCollection("blog").path(path).first()
  return entry && (await renderEntry(entry)).html
}

To render with your library's components, use ContentRenderer from @hamur/content/<library>. It is in all six adapters.

PropDefaultMeaning
valuerequireda page entry, which renders its body, or a Markdown AST
components{}Markdown components by kebab-case name and prose components by Prose<Tag>; false uses only the files and the defaults
tag"div"the wrapper element
excerptfalserender the entry's excerpt instead of its body; an entry without one renders nothing
unwrapnonespace-separated tags to drop and keep their children, "p"

Heading anchors come from markdown.headingLinks; ContentRenderer has no option of its own. A missing value throws ContentRenderer: value is required under hamur dev and renders nothing in a build. It writes no html node, so markdown.html: true content is left out of it.

Prose components

A prose component replaces one Markdown element: Prose<Tag> with the tag in PascalCase, from ProseA, ProseH1 to ProseH6, ProseP, ProseUl, ProseOl, ProseLi, ProseBlockquote, ProsePre, ProseCode, ProseImg, ProseTable, ProseHr, ProseStrong and ProseEm. The defaults write the plain element, with ProseA using Link for an internal URL, so a document looks as MarkdownRenderer writes it. ProsePre also gets language, filename, highlights and code, the source text, for a copy button. The components prop wins over a file, and a file over the default. A task-list item always renders as the plain element.

Override one for the whole app by writing app/components/content/Prose<Tag>.<ext>. The file applies to every ContentRenderer, every MarkdownRenderer and every Markdown page. The extension is your library's:

LibraryFileReceives
React, PreactProseA.tsxprops and children
SolidProseA.tsxprops and children
VueProseA.vueprops and the default slot
SvelteProseA.svelteprops and the children snippet
htmlProseA.ts(props) => string, with children as a string
tsx
import { Link } from "@hamur/adapter-react"
import type { ReactNode } from "react"

export default function ProseA({ href = "#", children }: { href?: string; children?: ReactNode }) {
  return href.startsWith("/") ? (
    <Link to={href} className="docs-link">
      {children}
    </Link>
  ) : (
    <a href={href} className="docs-link external">
      {children}
    </a>
  )
}

A file whose name is Prose plus something that is not a Markdown element fails the build: app/components/content/ProseFoo.tsx: "foo" is not a Markdown element; a Markdown component is named in kebab case in Markdown and in PascalCase here (Foo.tsx).

A page for each entry

One catch-all page maps a page collection to routes. useContentPage(collection) loads the entry whose path is the route path, sets the head from the entry's seo, and throws a 404 Page not found: <path> when there is none.

ts
import { ContentRenderer, useContentPage } from "@hamur/content/html"

export default function Page(): string {
  const page = useContentPage("docs")
  return `<main>${page ? ContentRenderer({ value: page }) : ""}</main>`
}
tsx
import { ContentRenderer, useContentPage } from "@hamur/content/react"

export default function Page() {
  const page = useContentPage("docs")
  return <ContentRenderer value={page} />
}

The return value follows the library, as useAsyncData does: React gives the entry and suspends while it loads; Vue gives Promise<ComputedRef<entry>> for await useContentPage(…) in setup; Solid an accessor; Preact and html the entry or undefined while it loads; Svelte { readonly page }. A collection that a catch-all serves must be exposed, because the browser queries it on a client navigation. useContentPage on a data collection throws useContentPage("authors"): a data collection has no paths.

With content.prerender on (the default on static), hamur generate writes every page path of every page collection, drafts left out, and a path with no entry answers the 404 page. With @hamur/seo the paths are sitemap seeds; without prerender, list them in a seo.sitemap.sources handler that queries the collection. There is no route table generated from collections in v1: the catch-all page is where you choose the route, and a renamed content path needs a redirects entry.

Queries

queryCollection(name) from @hamur/content/query builds a query. It runs in process on the server, in a load, a handler or a server render, and in the browser through clientQuery. From a handler you may also use queryCollection(event, name) of @hamur/content/server. The root @hamur/content is the module and imports the build, so import queries from /query.

ts
import { queryCollection } from "@hamur/content/query"

export const recent = () =>
  queryCollection("blog")
    .where("date", ">=", "2026-01-01")
    .andWhere((group) => group.where("tags", "IN", ["news"]).orWhere("title", "LIKE", "Hamur%"))
    .select("title", "path", "date")
    .order("date", "DESC")
    .limit(10)
    .all()

export const page = (path: string) => queryCollection("blog").path(path).first()

export const total = () => queryCollection("blog").where("draft", "=", false).count()

where, andWhere and orWhere combine left to right (where is andWhere), and a callback makes a group. A field is a name or a dotted path into an object (author.name). order calls stack, the first sorting first. select limits the fields and always returns id. count() counts the matches. Results are copies: editing one never changes the store.

OperatorValueMatches
=, <>scalarequal, not equal
>, >=, <, <=scalarordered comparison
IN, NOT INarray of at most 1000equal to one, to none
BETWEEN, NOT BETWEEN[low, high]>= low AND <= high, its negation
IS NULL, IS NOT NULLnonenull or missing; present and not null
LIKE, NOT LIKEstring of at most 200 characters% any run, _ one character, ASCII case-insensitive

The engine follows SQLite's rules. A comparison with null or a missing field is never true, <> included. Values of different JSON types are never equal. Strings compare by code point and numbers as numbers. IN on an array field matches when any element is in the list, so tags IN ["news"] is the usual tag test. order puts nulls first ascending and last descending. A field must be a built field or a key some entry has, else unknown field "nope" in collection "blog"; no segment may be __proto__, constructor or prototype.

Under "api" the browser posts a JSON description of the calls, never code, to /_hamur/content/query, which checks it against the collection: 100 conditions, groups 8 deep, 100 select fields and 10 order fields at most. An unknown collection, field or operator answers 400 with { message }, and a body above server.maxBodySize 413. A collection with expose: false is refused there, and in the browser the call throws queryCollection("authors"): the collection is not exposed to the client (expose: false).

Typegen writes .hamur/types/content.d.ts and keeps each collection's item type from its schema, so queryCollection("blog") accepts only its field names and returns date: string. queryCollection<{ title: string }>("blog") types an entry by hand. When a schema has ~standard.jsonSchema, typegen also writes .hamur/content/schemas/<collection>.schema.json and .hamur/content/schemas.json, which maps globs to schema files for the yaml.schemas and json.schemas settings of an editor. Without JSON Schema the build logs [content] blog: schema has no JSON Schema; no editor schema written.

queryCollectionNavigation("docs", extraFields?) returns the tree of a page collection by directory, in source order. Each item is { title, path, stem, icon?, children?, …extraFields }.

A directory's title is its .navigation.yml title, else the title of its index page, else the directory name without its number prefix, with - as spaces and a capital first letter. A page with navigation: false is left out, and an index page with it hides its directory. navigation: { title, icon } renames a page.

yml
title: Guide
icon: i-book
order: 1

A .navigation.yml holds title, icon, order (a number that replaces the directory's number prefix when siblings sort) and fields to copy as extra fields. Dot files are not watched, so under hamur dev save a page of that directory after editing it.

ts
import { findPageBreadcrumb, queryCollectionItemSurroundings, queryCollectionNavigation } from "@hamur/content/query"

export async function around(path: string) {
  const tree = await queryCollectionNavigation("docs", ["description"])
  const [previous, next] = await queryCollectionItemSurroundings("docs", path, { fields: ["title"] })
  return { crumbs: findPageBreadcrumb(tree, path), previous, next }
}

queryCollectionItemSurroundings(name, path, { before?, after?, fields? }) returns the entries before and after a path in the collection's order, null where there is none. findPageHeadline, findPageBreadcrumb, findPageChildren and findPageSiblings are pure functions over the tree.

content.search: { collections: ["docs"] } builds a search index for each listed collection at build. Each must be an exposed page collection. The index covers sections, a page cut at its headings (queryCollectionSearchSections(name, { ignoredTags?, minHeading?, maxHeading? }) is the same cut), with code blocks left out. Terms are lower-cased and stripped of diacritics, the last query term matches by prefix, terms combine as OR, and results are ranked by BM25 with the title weighing 5. There is no fuzzy matching and no snippet. Search runs in the browser, and in a handler as searchCollection(event, name, query, { limit? }) from @hamur/content/server, which reads the same index. The index is a lazy module, loaded on the first search(); useSearchCollection("docs", { immediate? }) from @hamur/content/<library> returns { status, search, init }, with status in the form of your library, and each hit is { id, title, titles, level, score }, where id is <path>#<heading id>.

tsx
import { useSearchCollection, type SearchHit } from "@hamur/content/react"
import { useState } from "react"

export function SearchBox() {
  const { status, search } = useSearchCollection("docs")
  const [hits, setHits] = useState<SearchHit[]>([])
  return (
    <div>
      <input type="search" onChange={async (event) => setHits(await search(event.target.value, { limit: 8 }))} />
      {status === "loading" && <p>Loading the index</p>}
      <ul>
        {hits.map((hit) => (
          <li key={hit.id}>
            <a href={hit.id}>{hit.titles.concat(hit.title).join(" > ")}</a>
          </li>
        ))}
      </ul>
    </div>
  )
}

A collection not in content.search.collections throws useSearchCollection("docs"): add "docs" to content.search.collections.

Live collections

A live collection is read at request time by your own loader, validated by its schema, and never written to the index. defineLiveCollection({ loader, schema? }) takes loadCollection(filter) and loadEntry(filter).

ts
import { defineContentConfig, defineLiveCollection } from "@hamur/content"

interface Post {
  id: string
  title: string
}

export default defineContentConfig({
  collections: {
    posts: defineLiveCollection({
      loader: {
        name: "cms",
        async loadCollection(filter?: { tag?: string }) {
          const query = filter?.tag ? `?tag=${encodeURIComponent(filter.tag)}` : ""
          const items = (await (await fetch(`https://cms.example.com/posts${query}`)).json()) as Post[]
          return {
            entries: items.map((item) => ({ id: item.id, data: item })),
            cacheHint: { tags: ["posts"], maxAge: 300 },
          }
        },
        async loadEntry(filter: { id: string }) {
          const response = await fetch(`https://cms.example.com/posts/${filter.id}`)
          if (!response.ok) return undefined
          const item = (await response.json()) as Post
          return { id: item.id, data: item }
        },
      },
    }),
  },
})

Read it on the server with getLiveCollection(name, filter) and getLiveEntry(name, filter) from @hamur/content/server. They return { entries | entry, error, cacheHint } and never throw for what the loader or the schema does: an invalid entry or a loader that throws is error.

ts
import { getLiveCollection, refreshContent } from "@hamur/content/server"
import { createError, defineHandler } from "hamur/server"

export const posts = defineHandler({
  route: "/api/posts",
  method: "GET",
  async handler() {
    const { entries, error } = await getLiveCollection("posts", { tag: "news" })
    if (error) throw createError({ status: 502, message: error.message })
    return entries.map((entry) => entry.data)
  },
})

export const cmsWebhook = defineHandler({
  route: "/api/webhooks/cms",
  method: "POST",
  raw: true,
  async handler() {
    await refreshContent({ collections: ["posts"] })
    return new Response(null, { status: 204 })
  },
})
  • Cache. A result without an error and with cacheHint.maxAge above 0 is kept in the cache storage mount for that many seconds, under content:live:<collection>:<hash of the call and its filter>. The filter must be plain JSON.
  • Refresh. refreshContent({ collections? }) drops the cached results, so a CMS webhook handler can call it. With a shared storage driver it reaches every instance's cache, but a load that was in flight on another instance may store its stale result until its maxAge.
  • Markdown bodies. A string body is Markdown and is parsed at run time only where Bun.markdown exists: the bun preset and hamur dev. Elsewhere it is the entry's error; return a Markdown AST instead. The run-time parse uses the parser's defaults, not the markdown key.
  • Dev. In hamur dev, POST /_hamur/content/refresh runs the build-time loaders again and drops the live results, and answers 204. Use it as a CMS webhook target.

REST, OpenAPI and GraphQL

content.api.rest: true serves GET <baseURL>api/_content/<collection> for every exposed collection, and lists the routes in /_hamur/openapi.json when server.openapi is on. content.api.graphql: true adds the collections to the app's GraphQL schema when server.graphql is on. REST needs a server, so rest: true on the static preset fails with content.api.rest needs a server; the static preset serves no route.

Query stringMeaning
where[field]=vfield = v
where[field][op]=van operator of the table above, in lower or upper case, URL-encoded
order=field:desccomma-separated or repeated; field alone is ascending
limit, skipdigits; limit is 100 when absent and a larger value is cut to 100

A value is read as JSON when it parses to a scalar or an array, else as text, so where[draft]=false is a boolean. Several where parameters join with AND. Anything else is a 400: unknown query parameter "select"; use where[field], where[field][operator], order, limit and skip. An unknown and an unexposed collection both answer 404 unknown collection "authors".

Each route's OpenAPI entry uses the collection schema's output JSON Schema with the built fields merged in, the operation id getContent<Name> and the tag content. With GraphQL, each exposed collection blog becomes the type Blog, Query.blog(where, order, limit, skip) and Query.blogItem(path) ((id) for a data collection). Field types come from the schema's JSON Schema; a type GraphQL cannot name, and the page fields seo, body, toc and the like, are JSON text in a String. A clash of type or query names fails the build and names both collections. A live collection has neither.

Raw Markdown and llms.txt

content.raw: true serves each page's source file at <path>.md, as text/markdown; charset=utf-8, with the frontmatter in it; / is /index.md. content.llms writes /llms.txt, in the llmstxt.org layout: a title, a description and, for each section, a list of [title](URL): description lines of the pages its query returns, drafts left out. content.raw: "body" serves what the collection's loader gave as the page's body instead of the file: a loader that resolves includes, as this site's does, gives a page with its code samples in place, where true would serve the @include lines. With content.raw on, useContentPage adds <link rel="alternate" type="text/markdown" href="<app.baseURL><path>.md"> to the head. /llms-full.txt joins the sources of the listed pages with a --- line. URLs are made of site.url, app.baseURL and the path, so content.llms without site.url fails: content.llms needs site.url for absolute page URLs.

Both are public files written at build, so every preset serves them and static output contains them; they are not served by hamur dev. The bytes are the source files as on disk; transformers and hooks do not change them. A file that public/ or another module also gives fails the build and names both.

Content with @hamur/i18n

Content does not know about locales. One collection per locale, with the locale in the prefix, gives each locale its own paths, and the pages @hamur/i18n copies to /fr/… find them. examples/content-i18n/ has English and French content:

ts
import { defineCollection, defineContentConfig } from "@hamur/content"

export default defineContentConfig({
  collections: {
    docsEn: defineCollection({ type: "page", source: { include: "**/*.md", cwd: "en", prefix: "/" } }),
    docsFr: defineCollection({ type: "page", source: { include: "**/*.md", cwd: "fr", prefix: "/fr" } }),
  },
})

A helper, localizedCollection("docs", locale), takes the route path, strips the locale's prefix, reads the locale's collection and then the default locale's. The page shows the English entry under a notice, translated through t(), when a French file is missing: /fr/guide shows content/en/guide.md while content/fr/guide.md does not exist. Adding the French file replaces it with no other change. The html page of the example is a [[...slug]] catch-all, which @hamur/i18n copies per locale.

Errors

CaseMessage
no content.config.ts@hamur/content needs content.config.ts in <rootDir>
source and loader both, or neithercontent.config.ts: collection "blog" sets source and loader; set one
a type that is not page or datacontent.config.ts: collection "blog": type must be "page" or "data" (got "pages")
a schema failurecontent/blog/a.md: date: Expected string
a value that is not JSONcontent/blog/a.md: date: a schema output must be JSON (got function)
queryCollection before the store loadsqueryCollection: the content store is not loaded; add @hamur/content to modules
a data collection renderedrenderEntry needs a page collection entry (got data collection "authors")
no entry for the routethe 404 Page not found: /docs/nope
a live loader that throwsgetLiveCollection("posts"): loader "cms" failed: <message>

Not in v1

  • MDX, and a visual editor for content.
  • SQL storage and a database source; read a database in a loader at build, or use a live collection.
  • Joins between collections (query the second by the first's ids), SQL text queries and aggregates other than count.
  • Typo-tolerant search, search on the server, REST writes, GraphQL mutations and subscriptions.
  • content/ from layers: a layer's content.config.ts and files are not merged.
  • Collections as code in the client bundle (import blog from "#content/blog").