# Content Hooks

Plugin hooks that render and transform pages.

Content hooks render the pages of a [content source](/content-sources#custom-sources), and change page data, frontmatter, the page tree and Markdown. `defineDocs()` already renders its pages, so the `getPage*` hooks are for custom sources.

Each `getPage*` hook receives a page, and the latest plugin to return something other than `undefined` wins. So a plugin checks `page.type`, which is the key its source has in `createSite()`:

```ts title="vuesho.config.ts"
import { createSite, type Source } from "vuesho/config";
import { defineDocs } from "vuesho/content";

type Release = { title: string; date: string; html: string };

const docs = defineDocs();
const changelog: Source<{ pageData: Release; metaData: {} }> = {
  files: [
    {
      type: "page",
      path: "changelog/0.2.0.md",
      data: { title: "v0.2.0", date: "2026-11-01", html: "<p>Custom content sources.</p>" },
    },
  ],
};

export default createSite({ docs: docs.toSource(), changelog }).plugins({
  name: "acme:changelog",
  getPageBody(page) {
    if (page.type === "changelog") return { html: page.data.html };
  },
  getPageText(page) {
    if (page.type === "changelog") return page.data.html.replace(/<[^>]+>/g, "");
  },
  getPageLastModified(page) {
    if (page.type === "changelog") return new Date(page.data.date);
  },
});
```

### ContentHooks

| Prop                     | Type                                                                                                                                   | Description                                                                                            |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `getPageBody?`           | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<PageBody<never> \| undefined>) \| undefined` | The page's content. Without it, the page renders from its data.                                        |
| `getPageToc?`            | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<TOCEntry[] \| undefined>) \| undefined`      | The page's table of contents.                                                                          |
| `getPageText?`           | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<string \| undefined>) \| undefined`          | The page's text as Markdown, which goes under the title and description that `getPageMarkdown()` adds. |
| `getPageStructuredData?` | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<StructuredData \| undefined>) \| undefined`  | The headings and the text under each, for search.                                                      |
| `getPageLastModified?`   | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<Date \| undefined>) \| undefined`            | When the page last changed, for its page data, the sitemap and feeds.                                  |
| `getPageCreatedAt?`      | `((this: Context<AppShape>, page: Page<string \| undefined, SourcePageData>) => Awaitable<Date \| undefined>) \| undefined`            | When the page was written, for feeds and blogs.                                                        |

A page that has an `absolutePath` uses that file for its edit link. `getPageStructuredData` returns the headings and text that search indexes:

```ts
getPageStructuredData(page) {
  if (page.type !== "changelog") return;
  return { headings: [], contents: [{ content: page.data.html.replace(/<[^>]+>/g, "") }] };
},
```

## Page Bodies [#page-bodies]

`getPageBody` returns HTML, or the name and props of a body component from the plugin's theme:

```ts tab="HTML"
getPageBody: (page) => ({ html: "<p>Rendered as HTML.</p>" }),
```

```ts tab="Component"
getPageBody: (page) => ({ type: "card", props: { heading: "Hello", items: ["One"] } }),
```

`Plugin<C, { bodies }>` types the props, and the theme module maps each body to a component under `bodies`. The props reach the browser as JSON on every page load, so keep them small:

```ts tab="src/cards/plugin.ts"
import type { AppShape, Plugin } from "vuesho/config";

export interface CardProps {
  heading: string;
  items: string[];
}

export function cardsPlugin<C extends AppShape>(
  source: NoInfer<C["source"]>,
): Plugin<C, { bodies: { card: CardProps } }> {
  return {
    name: "acme:cards",
    theme: "/src/cards/theme.ts",
    getPageBody(page) {
      if (page.type !== source) return;
      const { heading, items } = page.data as Partial<CardProps>;
      if (heading && items) return { type: "card", props: { heading, items } };
    },
  };
}
```

```ts tab="src/cards/theme.ts"
import type { PluginTheme } from "vuesho/client";
import type { CardProps } from "./plugin";

export default {
  bodies: { card: () => import("./Card.vue") },
} satisfies PluginTheme<{ bodies: { card: CardProps } }>;
```

A site replaces a body component in its [theme](/theme#views-and-page-bodies)'s `bodies`. On a page from a Markdown collection, `page.data` keeps only the fields that the collection's schema and the plugins' [`frontmatter`](#frontmatter-fields) declare.

`highlightCode()` from `vuesho/highlight` highlights code on the server, for a body's props. Code in an unsupported language stays plain text:

```ts tab="plugin.ts"
import { highlightCode } from "vuesho/highlight";

const code = await highlightCode("const a = 1;", { lang: "ts" });
```

```vue tab="CodeCard.vue"
<script setup lang="ts">
import type { HighlightedCode } from "vuesho/highlight";

defineProps<{ code: HighlightedCode }>();
</script>

<template>
  <pre v-bind="code.pre"><code v-bind="code.code" v-html="code.html" /></pre>
</template>
```

## Page Data [#page-data]

Page data is what the browser receives about a page, in `usePage().value.pageData`. `transformPage` returns the fields to change, and `undefined` unsets a field:

```ts
transformPage(_data, { path }) {
  // No edit link on the generated reference.
  if (path.startsWith("/reference/")) return { githubUrl: undefined };
},
```

### PageData

| Prop            | Type                               | Description                                                                                                                                                                                         |
| --------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `title?`        | `string \| undefined`              | The page's title.                                                                                                                                                                                   |
| `description?`  | `string \| undefined`              | The page's summary or meta description.                                                                                                                                                             |
| `full?`         | `boolean \| undefined`             | Uses the page's full width.                                                                                                                                                                         |
| `githubUrl?`    | `string \| undefined`              | The URL of the page's file on the `site.git` host.                                                                                                                                                  |
| `lastModified?` | `string \| undefined`              | When the content last changed, as an ISO date.                                                                                                                                                      |
| `markdownUrl?`  | `string \| undefined`              | The URL of the page's Markdown.                                                                                                                                                                     |
| `noindex?`      | `boolean \| undefined`             | Keeps the page out of search engines and of every list of pages, like the sitemap, the feeds, `llms.txt` and the search. A page shown in the fallback language stays in the search of its language. |
| `colorMode?`    | `ColorModePreference \| undefined` | The page's color mode, which the reader can't change on it.                                                                                                                                         |
| `layout?`       | `string \| undefined`              | The `layout` from a content page's data, when it's a string.                                                                                                                                        |
| `dataRoutes?`   | `string[] \| undefined`            | The paths of the data routes the page reads, which a navigation loads before showing the page.                                                                                                      |

A plugin declares a new field in its types, and a site reads the field's type as `PageOf<typeof app, "docs">["pageData"]["readingTime"]`. The value must be JSON:

```ts title="reading-time-plugin.ts"
import type { AppShape, Plugin } from "vuesho/config";

export function readingTimePlugin<C extends AppShape>(): Plugin<
  C,
  { pageData: { /** Reading time in minutes. */ readingTime?: number } } // [!code highlight]
> {
  return {
    name: "acme:reading-time",
    async transformPage(_data, { page }) {
      const text = page && (await this.getPageText(page));
      if (text) return { readingTime: Math.ceil(text.split(/\s+/).length / 200) };
    },
  };
}
```

To compute a field from the tokens while the page compiles, use [a Markdown rule](/markdown-extensions#computing-page-data) instead.

## Frontmatter Fields [#frontmatter-fields]

`frontmatter` declares fields and their schemas. Vuesho validates them on every page, adds them to the JSON schema that editors read, and types them in `PageOf<typeof app, "docs">["data"]`:

```ts title="deprecation-plugin.ts"
import type { AppShape, Plugin } from "vuesho/config";
import { z } from "zod";

const status = z.enum(["beta", "deprecated"]);

export function deprecationPlugin<C extends AppShape>(): Plugin<
  C,
  { frontmatter: { status?: z.infer<typeof status> } }
> {
  return {
    name: "acme:deprecation",
    frontmatter: { status }, // [!code highlight]
    transformPage(_data, { page }) {
      const value = page && (page.data as { status?: string }).status;
      if (value === "deprecated") return { noindex: true };
    },
  };
}
```

A custom source validates its frontmatter with `validateFrontmatter()`, which adds the plugins' fields to a schema:

```ts
import { getSiteContext } from "vuesho/config";
import { defaultPageSchema } from "vuesho/content";
import { parseFrontmatter } from "vuesho/markdown";

async function pageData(text: string) {
  const { data } = parseFrontmatter(text);
  return getSiteContext().validateFrontmatter(defaultPageSchema, data);
}
```

## Loader Hooks [#loader-hooks]

`init`, `configureLoader` and `configure` run once, in that order, when the site starts. They don't run again when a dynamic source reloads.

`configureLoader` receives `createSite()`'s options and returns the ones it changes.

`configure` runs after the content loads, so it can check the content. An error thrown there stops the site:

```ts
configure() {
  for (const page of this.getPages()) {
    if (!page.data.title) throw new Error(`${page.path} has no title`);
  }
},
```

`transformStorage` and `transformPageTree` run every time the content loads, in plugin order. `transformStorage` changes a language's files before the page tree is built:

```ts
transformStorage({ storage }) {
  for (const path of storage.getFiles()) {
    if (path.split("/").some((part) => part.startsWith("_"))) storage.delete(path);
  }
},
```

## Page Tree [#page-tree]

`transformPageTree` changes page tree nodes, after the `pageTree.transformers` of `createSite()`. A transformer can set a name or an icon to a string, a component or a VNode. Other node fields reach [`usePageTree()`](/client-api#usepagetree) when their values are JSON:

```ts title="vuesho.config.ts"
import { h } from "vue";

createSite(docs.toSource()).plugins({
  name: "acme:code-titles",
  transformPageTree: {
    file(node) {
      if (typeof node.name === "string" && node.name.endsWith("()")) {
        return { ...node, name: h("code", node.name), kind: "function" }; // [!code highlight]
      }
      return node;
    },
  },
});
```

Inside a transformer, `this` holds the storage, the language and the tree's texts:

### PageTreeTransformerContext

| Prop        | Type                                                                                                                          | Description                                                |
| ----------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| `builder`   | `{ resolveFlattenPath(name: string, format: string): string; root(id?: string, path?: string): PageTree.Root; }`              |                                                            |
| `storage`   | `ContentStorage<Page<string \| undefined, SourcePageData>, Meta<string \| undefined, MetaData>>`                              | The file storage of every source, for the tree's language. |
| `storages?` | `Record<string, ContentStorage<Page<string \| undefined, SourcePageData>, Meta<string \| undefined, MetaData>>> \| undefined` |                                                            |
| `locale?`   | `string \| undefined`                                                                                                         |                                                            |
| `custom?`   | `Record<string, unknown> \| undefined`                                                                                        |                                                            |
| `options`   | `PageTreeOptions`                                                                                                             |                                                            |
| `texts`     | `Readonly<Record<string, string>>`                                                                                            | The tree language's texts, by key.                         |

## Markdown Transforms [#markdown-transforms]

`transformPageMarkdown` changes a page's Markdown, which `<page>.md`, `llms-full.txt` and AI tools read. Each plugin receives the Markdown the previous one returned, and returning `undefined` keeps it:

```ts
transformPageMarkdown(markdown, { path }) {
  return `${markdown}\n\n[Read this page on the site](${this.absoluteUrl(path)})`;
},
```

The second argument also has the page, its page data and `text`, which is the Markdown without the title and description.

## Rendering Markdown [#rendering-markdown]

`defineDocs()` compiles Markdown when the site builds. Markdown that the server receives, like a CMS's posts, renders with your own [markdown-it](https://github.com/markdown-it/markdown-it) and these exports of `vuesho/markdown`:

- `pageMarkdownSyntax` adds GFM, footnotes and the pages' heading IDs, with `[#id]` and `[!toc]`.
- `buildToc()` and `extractStructuredData()` return the table of contents and the search data of the parsed tokens.

```npm
npm i markdown-it
```

This site renders each post's Markdown to HTML, and reads the table of contents and the search data from its tokens:

```ts title="vuesho.config.ts"
import markdownIt from "markdown-it";
import { createSite } from "vuesho/config";
import { highlightCode } from "vuesho/highlight";
import { pageMarkdownSyntax, extractStructuredData, buildToc } from "vuesho/markdown";

// A symbol key keeps the Markdown on the server.
const body = Symbol("body");
// HTML stays off, so HTML tags in the Markdown render as text.
const md = markdownIt({ linkify: true }).use(pageMarkdownSyntax);

// markdown-it highlights synchronously, so the code blocks are highlighted with your code themes before it renders.
async function render(text: string) {
  const tokens = md.parse(text, {});
  const blocks = new Map<string, string>();
  for (const { type, info, content } of tokens) {
    if (type !== "fence") continue;
    const { pre, html } = await highlightCode(content, { lang: info.split(" ")[0] || "text" });
    const attributes = Object.entries(pre).map(
      ([name, value]) => ` ${name}="${md.utils.escapeHtml(value)}"`,
    );
    blocks.set(content, `<pre${attributes.join("")}><code>${html}</code></pre>`);
  }
  return md.renderer.render(
    tokens,
    { ...md.options, highlight: (code) => blocks.get(code) ?? "" },
    {},
  );
}

async function listPosts() {
  const response = await fetch("https://cms.example.com/posts");
  const posts: { slug: string; title: string; body: string }[] = await response.json();

  return posts.map((post) => ({
    type: "page" as const,
    path: `${post.slug}.md`,
    data: { title: post.title, [body]: post.body },
  }));
}

export default createSite({ posts: { files: listPosts, staleTime: 60_000 } }).plugins({
  name: "acme:posts",
  async getPageBody(page) {
    if (page.type === "posts") return { html: await render(page.data[body]) };
  },
  getPageToc(page) {
    if (page.type === "posts") return buildToc(md.parse(page.data[body], {}));
  },
  getPageStructuredData(page) {
    if (page.type === "posts") return extractStructuredData(md.parse(page.data[body], {}));
  },
  getPageText(page) {
    if (page.type === "posts") return page.data[body];
  },
});
```

Your markdown-it instance uses only the `highlight` option of the config's `markdown`, through `highlightCode()`, so add markdown-it plugins to it with `use()`. To render components, like `<Callout>`, return a body component instead, as [Page Bodies](#page-bodies) shows.
