# Dynamic Rendering

Pages rendered on request, with caching.

Pages render to HTML when the site builds, unless they need a server. A page rendered on request can show content that changes, like a CMS's pages, without a new build.

## Render Modes [#render-modes]

Local Markdown pages render when the site builds. These pages render on request, so they need a server:

- the pages of a [dynamic source](#dynamic-sources), which the server reads while the site runs
- a [custom page](/custom-pages) with `render: "dynamic"`, or with params and no `staticParams`
- a plugin's API route without `render: "static"`, like the [AI chat's](/ai#ai-chat)

To change the mode by path, set Nitro's route rules in `vite.config.ts`:

```ts title="vite.config.ts"
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";

export default defineConfig({
  plugins: [vuesho()],
  nitro: {
    routeRules: {
      "/changelog/**": { prerender: false }, // Rendered on request
      "/changelog/archive": { prerender: true }, // Rendered when the site builds
    },
  },
});
```

The most specific pattern wins, and `/changelog/**` also matches `/changelog`. All pages that one file with [path params](/routing#path-params) generates share one mode. Nitro's `prerender.routes`, `crawlLinks` and `ignore` aren't supported.

## Dynamic Sources [#dynamic-sources]

A dynamic source is a [content source](/content-sources) whose `files` is a function. The function reads the files on the server, and returns the same objects as a `files` array:

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

type PostFile = SourceFile<{ pageData: { title: string; html: string }; metaData: {} }>;

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

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

export default createSite({ files: listPosts, staleTime: 60_000 }).plugins({
  name: "site:posts",
  getPageBody: (page) => ({ html: page.data.html }),
});
```

A dynamic source's pages render on request, so the site needs a server. The routes that list every page, like the sitemap and the search index, render on request too. To change the mode for a path, use a [route rule](#render-modes).

A static build reads a dynamic source once, when the site builds, and writes its pages as HTML. The pages then change only with the next build.

### Mixing Static and Dynamic Sources [#mixing-static-and-dynamic-sources]

A site with [multiple sources](/markdown/collections#multiple-collections) can mix both kinds. The Markdown in your repository stays prerendered, while the CMS's pages render on request:

```ts title="vuesho.config.ts"
createSite({
  docs: docs.toSource(),
  posts: { baseDir: "posts", files: listPosts, staleTime: 60_000 }, // [!code highlight]
}).plugins({
  name: "site:posts",
  getPageBody(page) {
    if (page.type === "posts") return { html: page.data.html };
  },
});
```

## Refreshing Content [#refreshing-content]

The server keeps the files in memory and reads them again in three cases:

```ts title="vuesho.config.ts"
// After a minute, the next request reads the files again. With 0, every request does
createSite({ files: listPosts, staleTime: 60_000 });

// In a plugin hook: read one source's files again now, by its key, or every source's
await this.revalidateLoader("posts");

// In a plugin hook: mark the files stale, so the next request reads them
this.invalidateLoader("posts");
```

In development, a refresh also reloads the page open in the browser.

### Webhooks [#webhooks]

With an API route, the CMS can refresh the pages when an author publishes. A secret keeps others from calling the route:

```ts title="vuesho.config.ts"
createSite({ files: listPosts }).plugins({
  name: "site:posts",
  getPageBody: (page) => ({ html: page.data.html }),
  // [!code ++:13]
  routes({ createApi }) {
    createApi({
      path: "/api/refresh",
      POST: async (request) => {
        const secret = process.env.REFRESH_SECRET;
        if (!secret || request.headers.get("Authorization") !== `Bearer ${secret}`) {
          return new Response("Unauthorized", { status: 401 });
        }
        await this.revalidateLoader();
        return new Response("Refreshed");
      },
    });
  },
});
```

<Callout type="warn" title="Several Server Instances">
`revalidateLoader()` and `invalidateLoader()` refresh the server instance that handles the request. On a serverless host, the other instances refresh once their `staleTime` passes, so a site on such a host sets a `staleTime` too.
</Callout>

## Caching [#caching]

A dynamic source with a `staleTime` sends `Cache-Control: public, s-maxage=<seconds>` with its pages, so a CDN keeps them as long as the server does. `staleTime: 0` sends no `Cache-Control`, and plugin middleware can set another one.

To set other cache headers, like for the images in `public/`, use the `headers` of a [route rule](/deploying#redirects-and-headers).

A Nitro `cache` route rule caches pages on the server, and `revalidateLoader()` doesn't clear that cache. On a dynamic source's pages, such a rule saves work per request, but readers see a change only once the cached page expires.

### CDN Purging [#cdn-purging]

A webhook route can purge the CDN too, so every reader sees a change at once. Middleware tags the cached responses, and the route purges the tag:

<Tabs :items='["Vercel","Netlify","Cloudflare"]'>
<Tab value="Vercel">
```npm
npm i @vercel/functions
```

```ts title="vuesho.config.ts"
import { addCacheTag, dangerouslyDeleteByTag } from "@vercel/functions"; // [!code ++]

createSite({ files: listPosts, staleTime: 3_600_000 }).plugins({
  name: "site:posts",
  getPageBody: (page) => ({ html: page.data.html }),
  // [!code ++:7]
  middleware: {
    async handle(_request, next) {
      const response = await next();
      if (response.headers.get("Cache-Control")?.includes("s-maxage")) await addCacheTag("posts");
      return response;
    },
  },
  routes({ createApi }) {
    createApi({
      path: "/api/refresh",
      POST: async (request) => {
        // Check the webhook's secret first.
        await this.revalidateLoader();
        await dangerouslyDeleteByTag("posts"); // [!code ++]
        return new Response("Refreshed");
      },
    });
  },
});
```

Both functions run only in middleware or an API route, where a request is active.
</Tab>

<Tab value="Netlify">
```npm
npm i @netlify/cache
```

```ts title="vuesho.config.ts"
import { purgeCache } from "@netlify/cache"; // [!code ++]

createSite({ files: listPosts, staleTime: 3_600_000 }).plugins({
  name: "site:posts",
  getPageBody: (page) => ({ html: page.data.html }),
  // [!code ++:10]
  middleware: {
    async handle(_request, next) {
      const response = await next();
      if (!response.headers.get("Cache-Control")?.includes("s-maxage")) return response;
      const { status, statusText, headers } = response;
      const tagged = new Response(response.body, { status, statusText, headers });
      tagged.headers.set("Cache-Tag", "posts");
      return tagged;
    },
  },
  routes({ createApi }) {
    createApi({
      path: "/api/refresh",
      POST: async (request) => {
        // Check the webhook's secret first.
        await this.revalidateLoader();
        await purgeCache({ tags: ["posts"] }); // [!code ++]
        return new Response("Refreshed");
      },
    });
  },
});
```

`purgeCache()` reads the site ID and a purge token from the environment that Netlify sets.
</Tab>

<Tab value="Cloudflare">
```ts title="vuesho.config.ts"
createSite({ files: listPosts, staleTime: 3_600_000 }).plugins({
  name: "site:posts",
  getPageBody: (page) => ({ html: page.data.html }),
  // [!code ++:10]
  middleware: {
    async handle(_request, next) {
      const response = await next();
      if (!response.headers.get("Cache-Control")?.includes("s-maxage")) return response;
      const { status, statusText, headers } = response;
      const tagged = new Response(response.body, { status, statusText, headers });
      tagged.headers.set("Cache-Tag", "posts");
      return tagged;
    },
  },
  routes({ createApi }) {
    createApi({
      path: "/api/refresh",
      POST: async (request) => {
        // Check the webhook's secret first.
        await this.revalidateLoader();
        // [!code ++:10]
        const { CLOUDFLARE_ZONE_ID: zone, CLOUDFLARE_API_TOKEN: token } = process.env;
        const purge = await fetch(
          `https://api.cloudflare.com/client/v4/zones/${zone}/purge_cache`,
          {
            method: "POST",
            headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
            body: JSON.stringify({ tags: ["posts"] }),
          },
        );
        if (!purge.ok) throw new Error(`The purge failed: ${purge.status}`);
        return new Response("Refreshed");
      },
    });
  },
});
```

This example purges a Cloudflare zone in front of a server. On Cloudflare Workers, purge the tag with the [Workers Cache API](https://developers.cloudflare.com/workers/cache/) instead, with `cache.purge({ tags: ["posts"] })` from `cloudflare:workers`.
</Tab>
</Tabs>

## Protected Pages [#protected-pages]

A host serves a static file without running the server, so a page that only some readers may see must render on request. Turn off prerendering for its path with a route rule:

```ts title="vite.config.ts"
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";

export default defineConfig({
  plugins: [vuesho()],
  nitro: { routeRules: { "/internal/**": { prerender: false } } }, // [!code highlight]
});
```

Plugin middleware then rejects a request without a session, and `filter` leaves the pages out of search and `llms.txt`:

```ts title="vuesho.config.ts"
declare function hasSession(request: Request): Promise<boolean>;

const isInternal = (path: string) => path === "/internal" || path.startsWith("/internal/");

createSite(docs.toSource()).plugins(
  recommendedPreset({
    search: { filter: ({ page }) => !isInternal(page.url) },
    llms: { filter: ({ page }) => !isInternal(page.url) },
  }),
  {
    name: "site:session",
    middleware: {
      // [!code highlight:5]
      async handle(request, next, { page }) {
        if (isInternal(page) && !(await hasSession(request))) {
          return new Response("Unauthorized", { status: 401 });
        }
        return next();
      },
    },
  },
);
```

Middleware gets the same `page` path for a page's HTML, its data and its `.md` file, so one check guards all three. Middleware that rejects a prerendered page fails the build, since a file can't be rejected.

<Callout type="warn" title="What Stays Public">
A page's images, the files in `public/`, the stylesheets and the scripts, with the components that pages use, stay public. So do the titles and URLs of the pages in the sidebar and the sitemap. To hide pages from the sidebar too, give the source an [audience](#audiences).
</Callout>

## Audiences [#audiences]

`audience` assigns each request an audience, like the reader's role, and `files` receives it. The pages, the sidebar, search and `llms.txt` then match each request's audience:

```ts title="vuesho.config.ts"
import { createSite } from "vuesho/config";
import { defineDocs } from "vuesho/content";
import { pageSchema } from "vuesho/schema";
import { z } from "zod";

declare function getSession(request: Request): Promise<{ staff: boolean } | undefined>;

const docs = defineDocs({
  docs: { schema: pageSchema.extend({ staff: z.boolean().default(false) }) },
});
const { files } = docs.toSource();

export default createSite({
  // [!code highlight:3]
  files: ({ audience }) =>
    files.filter((file) => file.type === "meta" || !file.data.staff || audience === "staff"),
  audience: {
    // The cookies `get` reads. A request without them is public.
    cookies: ["session"],
    get: async (request) => ((await getSession(request))?.staff ? "staff" : undefined),
  },
});
```

A request without a listed cookie gets the public pages, which a CDN can cache. A request with one gets its audience's pages, as a private response. A reader outside an audience gets a 404 for that audience's pages.

- `cookies` lists every cookie that `get` reads, with its prefix, like `__Secure-`.
- Keep audiences coarse, like a role or a preview, since the server keeps each audience's files in memory.
- A site with an audience needs a server: every content page renders on request, and a static build fails. A `prerender: true` route rule still prerenders the public pages.

With multiple sources, `audience` goes on one source, and the other sources show the same pages to every reader.

### Previews [#previews]

As a function, `staleTime` sets a separate time for each audience. A preview reads the drafts on each request, while the public pages stay cached:

```ts title="vuesho.config.ts"
// Calls to your CMS: the posts with or without drafts, and whether a request has a preview session.
declare function listPosts(options: { drafts: boolean }): Promise<SourceFile[]>;
declare function isPreview(request: Request): Promise<boolean>;

createSite({
  files: ({ audience }) => listPosts({ drafts: audience === "preview" }),
  staleTime: ({ audience }) => (audience === undefined ? 60_000 : 0), // [!code highlight]
  audience: {
    cookies: ["preview"],
    get: async (request) => ((await isPreview(request)) ? "preview" : undefined),
  },
});
```

### CDNs [#cdns]

Public responses vary on the `Cookie` header, so a CDN never gives a reader with an audience a cached public page, and Vercel's CDN caches none of them. To cache the public pages on the server, add a Nitro `cache` route rule with the audience's cookies in `allowCookies`, so it caches only the responses to requests without them:

```ts title="vite.config.ts"
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";

export default defineConfig({
  plugins: [vuesho()],
  nitro: {
    routeRules: { "/**": { cache: { maxAge: 60, allowCookies: ["session"] } } },
  },
});
```
