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
Local Markdown pages render when the site builds. These pages render on request, so they need a server:
- the pages of a dynamic source, which the server reads while the site runs
- a custom page with
render: "dynamic", or with params and nostaticParams - a plugin's API route without
render: "static", like the AI chat's
To change the mode by path, set Nitro's route rules in 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 generates share one mode. Nitro's prerender.routes, crawlLinks and ignore aren't supported.
Dynamic Sources
A dynamic source is a content source whose files is a function. The function reads the files on the server, and returns the same objects as a files array:
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.
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
A site with multiple sources can mix both kinds. The Markdown in your repository stays prerendered, while the CMS's pages render on request:
createSite({
docs: docs.toSource(),
posts: { baseDir: "posts", files: listPosts, staleTime: 60_000 },
}).plugins({
name: "site:posts",
getPageBody(page) {
if (page.type === "posts") return { html: page.data.html };
},
});Refreshing Content
The server keeps the files in memory and reads them again in three cases:
// 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
With an API route, the CMS can refresh the pages when an author publishes. A secret keeps others from calling the route:
createSite({ files: listPosts }).plugins({
name: "site:posts",
getPageBody: (page) => ({ html: page.data.html }),
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");
},
});
},
});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.
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.
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
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:
npm i @vercel/functionsimport { addCacheTag, dangerouslyDeleteByTag } from "@vercel/functions";
createSite({ files: listPosts, staleTime: 3_600_000 }).plugins({
name: "site:posts",
getPageBody: (page) => ({ html: page.data.html }),
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");
return new Response("Refreshed");
},
});
},
});Both functions run only in middleware or an API route, where a request is active.
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:
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";
export default defineConfig({
plugins: [vuesho()],
nitro: { routeRules: { "/internal/**": { prerender: false } } },
});Plugin middleware then rejects a request without a session, and filter leaves the pages out of search and llms.txt:
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: {
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.
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
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:
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({
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.
cookieslists every cookie thatgetreads, 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: trueroute 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
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:
// 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),
audience: {
cookies: ["preview"],
get: async (request) => ((await isPreview(request)) ? "preview" : undefined),
},
});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:
import { defineConfig } from "vite";
import vuesho from "vuesho/vite";
export default defineConfig({
plugins: [vuesho()],
nitro: {
routeRules: { "/**": { cache: { maxAge: 60, allowCookies: ["session"] } } },
},
});