# Content Sources: Bring Your Own CMS

> Read the blog, changelog or docs from a CMS or API instead of Markdown files: the ContentSource contract, sanitizing HTML on Workers, refresh, images and testing. WordPress as a worked example.

*Canonical: https://makerkit.dev/docs/void-cloudflare/marketing/content-sources*

---

By default a collection reads Markdown from the repository. Any collection can read from your own backend instead: a headless CMS (Sanity, Contentful, Strapi, WordPress…), a database or a JSON API. You write one small object, a `ContentSource`, and the pages, paging, feed, caching and validation keep working unchanged.

This page is part of the [Marketing documentation](./overview). Read [Blog and Changelog](./blog-and-changelog) first.

## How It Works

| | Repo (default) | Remote |
|---|---|---|
| Entries | `content/<collection>/*.md` | your `ContentSource` |
| Invalid entry | fails `pnpm test:unit` (CI) | left out of the site and logged |
| New and edited entries | on the next deploy | within about `2 × maxAge` seconds |
| Cached pages | until the next deploy | for `maxAge` seconds, then rendered again |
| Source down | n/a | cached pages keep serving; the last listing that worked is used |
| HTML | rendered as written (review PRs) | **your source must sanitize it** |

## 1. Write the Source

A source has a `kind`, lists its entries and renders one entry:

```ts
import type { ContentSource } from '@kit/content';

export function cmsSource(): ContentSource {
  return {
    kind: 'remote',

    // every entry: { id, slug, frontmatter } (may be sync or async)
    async list() {
      return [];
    },

    // one entry's sanitized HTML and its headings (async); undefined if the
    // entry no longer exists, which answers 404
    async render(slug) {
      return undefined;
    },
  };
}
```

- **`id`** names the entry in logs: your CMS's id (`cms:42`), never a value from the entry.
- **`slug`** is its URL under the collection: lowercase words joined by hyphens (`hello-world`); in the docs, up to three of them joined by `/` (`billing/payment-methods/cards`).
- **`frontmatter`** is an object the collection validates against its schema (below).
- **`render`** is called when a page renders (not on every view: rendered pages are cached). Return HTML you trust: the collection renders it as is.
- **`toc`**, returned by `render` with the HTML, lists the body's headings as `{ id, title, depth }` (`depth` 2 for `<h2>`), where `id` is the heading's `id` attribute. Return `[]` if you don't need a table of contents.

The collection does the rest: validation, drafts (`status: 'draft'` entries are hidden outside the dev server), order, paging, caching, and listing again after a failure.

### Map Your Fields to the Schema

The blog's schema expects `title`, `description`, `date` (ISO: `2026-11-02` or a datetime such as `2026-11-02T09:00:00`), and optionally `image`, `status` and `author`. Map your backend's fields to those names in `list()`, and make sure:

- text fields are plain text: strip HTML tags and decode entities (`&#8217;` → `’`). React escapes text, so leftover markup shows up literally;
- `description` is never empty (fall back to the title or the first sentence of the body);
- slugs are lowercase and hyphenated (a CMS may percent-encode non-Latin slugs; map or skip those);
- no extra fields: the schema is strict, so only pass the fields it knows (or extend it in `config/content.config.ts`).

An entry that still doesn't fit is **left out and logged** with its id, the failing fields and the zod issue codes (never field values: CMS content may hold drafts or personal data). Entries sharing a slug are all left out. The rest of the collection keeps working.

### Bodies That Aren't HTML

Many CMSs return structured bodies instead of HTML: Sanity's Portable Text, Contentful's Rich Text JSON, Markdown from a JSON API. Convert them to HTML in `render()` with the CMS's renderer (`@portabletext/to-html`, `@contentful/rich-text-html-renderer`) or a Markdown renderer that runs on Workers, **then sanitize the result**: renderers pass embedded HTML through.

### Page Through the API

Return every entry from `list()`: the collection pages the index itself. Most APIs cap a request (often at 100 items), so loop until the last page. Keep the listing light: request only the fields you map, and fetch bodies in `render(slug)` if the API lets you (or keep the bodies from the listing in a `Map` keyed by slug, as in the example).

Give every request a timeout (`fetch(url, { signal: AbortSignal.timeout(5000) })`): the last good listing is used only when `list()` fails, so a request that hangs stalls the page instead. After `maxAge`, each Worker isolate lists your API again (concurrent requests may each list it), so size `maxAge` to your API's rate limits.

### Sanitize the HTML (Required)

Content pages are served without a Content Security Policy to visitors without cookies, so a `<script>` or an `onerror=` attribute in a CMS post would run on your domain for every visitor. Sanitize in `render()` with an allowlist sanitizer that runs on Cloudflare Workers, which have no DOM: [`xss`](https://www.npmjs.com/package/xss) (js-xss) is pure JavaScript. DOMPurify needs a DOM and doesn't run there.

```ts
import xss from 'xss';

const { FilterXSS, getDefaultWhiteList } = xss;

const defaults = getDefaultWhiteList();

// tags and attributes allowed in a post body; scripts, styles, on* handlers
// and javascript: URLs are removed
const bodyFilter = new FilterXSS({
  whiteList: {
    ...defaults,
    // keep heading ids, so a toc can link to them
    h2: [...(defaults.h2 ?? []), 'id'],
    h3: [...(defaults.h3 ?? []), 'id'],
  },
  stripIgnoreTag: true,
  stripIgnoreTagBody: ['script', 'style'],
});

export const sanitizeBody = (html: string) => bodyFilter.process(html);
```

The default allowlist also drops `class` (so CMS code highlighting is lost), `srcset` and `<iframe>` embeds. Add only what you need, attribute by attribute; never allow `on*` attributes, `style`, or `<iframe>` without restricting its `src`. Fields rendered as text (`title`, `description`) are escaped by React and need no sanitizing.

### Read Secrets in the Source

Add your API URL and token to `apps/web/env.ts` (`import { defineEnv, url, string } from 'void/env'`) and read them through `env` from `void/env` **inside** `list()` and `render()`, never at the top of the module (see [Environment variables](../configuration/environment-variables)). Set them for the deployed Worker with `void secret put`.

## 2. Configure the Collection

In `apps/web/config/content.config.ts`, mark the collection as remote and say how long a listing stays fresh:

```ts
blog: {
  basePath: '/blog',
  schema: entrySchema.extend({ author: z.string().min(1).optional() }),
  kind: 'remote',
  // seconds: new and edited posts appear within about twice this
  maxAge: 300,
  // only if the `image` field points to your CMS's media host
  imageOrigins: ['https://cms.example.com'],
},
```

- **`kind: 'remote'`** turns off the CI check of `content/blog/` (there are no files) and validates at runtime instead.
- **`maxAge`** is required for a remote collection (`pnpm lint` flags a remote collection without it). After it, the next request lists your source again, and the pages tell Void's cache to keep them for as long (an `x-revalidate` header set by the kit's loaders). A post you publish appears within about `2 × maxAge` (one for the listing, one for the cached page), on the first request after that.
- **`imageOrigins`** lets the `image` field use absolute `https://` URLs from exactly these origins: scheme and host only, no trailing slash or path (`https://cms.example.com`, not `https://cms.example.com/`). Any other host fails validation, so a CMS can't slip in a tracking pixel. Add the same origins to `img-src` in `apps/web/config/security.config.ts`; a unit test fails until you do (otherwise images load for first-time visitors and break for everyone with a cookie, under the CSP). Images inside the body are your sanitizer's job, and need `img-src` too.

## 3. Pass the Source

In `apps/web/config/content.server.ts`, replace `globSource(…)` for that collection:

```ts
import { cmsSource } from './cms-source.server.ts';

export const blog = buildCollection({
  name: 'blog',
  includeDrafts: import.meta.env.DEV,
  source: cmsSource(),
});
```

If the config says `kind: 'remote'` but the source says otherwise (or the reverse), the app fails at startup with the fix in the message.

## 4. Test the Source

`pnpm test:unit` doesn't check remote collections (there are no files to read), so give your mapping its own test with a stubbed `fetch`:

```ts
// apps/web/config/__tests__/cms-source.server.test.ts
import { describe, expect, it, vi } from 'vite-plus/test';

import { buildCollection } from './content.config';
import { cmsSource } from './cms-source.server';

vi.mock('void/env', () => ({ env: { CMS_URL: 'https://cms.example.com' } }));

describe('cmsSource', () => {
  it('maps the API to valid entries', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => Response.json([/* one item, as your API returns it */])),
    );

    const blog = buildCollection({
      name: 'blog',
      source: cmsSource(),
      includeDrafts: true,
    });

    const [entry] = await blog.entries();

    expect(entry).toMatchObject({ slug: 'hello-world', title: 'Hello world' });
    expect((await blog.loadEntry('hello-world'))?.html).not.toContain('<script');
  });
});
```

## 5. Publishing, Deploys and Outages

- **Publishing** needs no deploy: a new post appears after the listing and the cached pages expire. Lower `maxAge` for faster updates.
- **Deploys** clear the cache. Each page renders on its first request after the deploy, then is cached for `maxAge`.
- **Outages:** visitors without cookies keep getting cached pages. If your API fails after a listing has worked, the last good listing keeps serving and the error is logged. A page that isn't cached yet, on a Worker isolate that has never listed your source, errors until the API is back.
- **Deleted entries** leave the index after the next listing and answer 404 once `render()` returns `undefined`: with bodies kept from the listing, that's within about `2 × maxAge` too.

## Worked Example: WordPress

One backend, to show the steps above end to end. Nothing in the kit is WordPress-specific; adapt the mapping for your API. Install the helpers first: `pnpm --filter web add xss he@^1.2.0` and `pnpm --filter web add -D @types/he`.

```ts
// apps/web/config/wordpress-source.server.ts
import he from 'he';
import { env } from 'void/env';
import xss from 'xss';

import type { ContentSource, SourceFile } from '@kit/content';

type WordPressPost = {
  id: number;
  slug: string;
  date_gmt: string;
  title: { rendered: string };
  excerpt: { rendered: string };
  content: { rendered: string };
};

const FIELDS = 'id,slug,date_gmt,title,excerpt,content';

const defaults = xss.getDefaultWhiteList();

const bodyFilter = new xss.FilterXSS({
  whiteList: {
    ...defaults,
    h2: [...(defaults.h2 ?? []), 'id'],
    h3: [...(defaults.h3 ?? []), 'id'],
  },
  stripIgnoreTag: true,
  stripIgnoreTagBody: ['script', 'style'],
});

const textFilter = new xss.FilterXSS({ whiteList: {}, stripIgnoreTag: true });

// "<p>Hello &#8217;world&#8217;</p>" → "Hello ’world’"
const plainText = (html: string) => he.decode(textFilter.process(html)).trim();

export function wordpressSource(): ContentSource {
  // bodies from the last listing, so a page render needs no second request
  const bodies = new Map<string, string>();

  return {
    kind: 'remote',

    async list() {
      const posts: WordPressPost[] = [];

      for (let page = 1, pages = 1; page <= pages; page++) {
        const url = `${env.WORDPRESS_URL}/wp-json/wp/v2/posts?per_page=100&page=${page}&_fields=${FIELDS}`;
        const response = await fetch(url, {
          signal: AbortSignal.timeout(5000),
        });

        if (!response.ok) {
          throw new Error(`WordPress listing failed: ${response.status}`);
        }

        pages = Number(response.headers.get('X-WP-TotalPages') ?? 1);
        posts.push(...((await response.json()) as WordPressPost[]));
      }

      bodies.clear();

      return posts.map((post): SourceFile => {
        bodies.set(post.slug, post.content.rendered);

        const title = plainText(post.title.rendered);
        const excerpt = plainText(post.excerpt.rendered);

        return {
          id: `wordpress:${post.id}`,
          slug: post.slug,
          frontmatter: {
            title,
            description: excerpt || title,
            // WordPress sends "2026-11-02T09:00:00" (GMT, no offset)
            date: post.date_gmt,
          },
        };
      });
    },

    async render(slug) {
      const body = bodies.get(slug);

      return body === undefined
        ? undefined
        : { html: bodyFilter.process(body), toc: [] };
    },
  };
}
```

Then:

1. Add `WORDPRESS_URL: url()` to `apps/web/env.ts` (import `url` from `void/env`) and set it in `apps/web/.env` and for the deployed Worker. It's not a secret, but `void secret put` sets it either way.
2. Set `kind: 'remote'` and `maxAge` on the collection (step 2).
3. Pass `wordpressSource()` instead of `cmsSource()` in `content.server.ts` (step 3).

The public WordPress API lists published posts only, so drafts stay in WordPress.

## Troubleshooting

| Symptom | Cause |
|---|---|
| `set maxAge (seconds) for a remote source` at startup | `kind: 'remote'` without `maxAge` in `content.config.ts` |
| `content.config.ts says kind 'repo', but content.server.ts passes a 'remote' source` | Add `kind: 'remote'` to the collection |
| `imageOrigins must be https origins like "https://cdn.example.com"` at startup | An origin with a path, a trailing slash or `http:` |
| An entry is missing; the logs show `content: skipped an invalid entry` | The log names the entry's `id` and its failing `fields`, e.g. `title (too_small)` |
| …with `fields: ["image (origin)"]` | The image's host isn't in `imageOrigins` |
| …with `fields: ["slug (format)"]` | The slug isn't lowercase words joined by hyphens |
| …with `fields: ["slug (duplicate)"]` | Two entries share a slug; both are left out |
| `content: listing failed, serving the last good listing` | Your API failed or timed out; the site keeps the last listing |
| Images show in a private window but not when signed in | The origin is missing from `img-src` in `security.config.ts` |
| A new post takes minutes to appear | Expected: up to about `2 × maxAge` |

---

**Back to:** [Marketing overview](./overview)
