Next.js
Render Graft content in a Next.js project, from install to cache refresh.
This guide adds Graft to a Next.js project. By the end, your pages read typed content, render its Markdown with your own components, and refresh only the pages whose content changed. The steps use the App Router. If your project uses the Pages Router, follow them up to the client, then use the Pages Router.
Before you start, you need a Next.js 15 or 16 project and a
graft.config.ts with compiled content. If you have not got those yet, run
through Getting started first. It takes about ten
minutes. Still on Next.js 14? Read
Run Graft on Next.js 14 first.
What @usegraft/sdk-next gives you:
- Typed reads. Every result is typed from your schema, in Server
Components, route handlers,
getStaticPropsandgetServerSideProps. - One read per document per request. If a layout and a page read the same
document, Graft reads it once, using
React.cache. - Markdown rendering on the server.
<MdxBody />renders a document's body without sending an MDX parser to the browser. - Targeted cache refresh.
revalidateContentrefreshes only the pages whose content changed.
Check your Next.js version
Graft supports Next.js 15 and 16, with the App Router or the Pages Router. What differs between them:
| Next.js 15 | Next.js 16 | |
|---|---|---|
| App Router and Pages Router | Yes | Yes |
| Cached reads you can refresh | unstable_cache | 'use cache' and cacheTag |
revalidateContent | Yes | Yes |
updateContent | No | Yes |
Graft does not refuse an older 15 or 16 release, but some are not safe to run.
15.5.24 and 16.3.3 are the first releases with fixes for the critical Next.js
advisories published in 2026. On a release without those fixes, withGraft
prints a warning when Next.js loads your config that names the release to
upgrade to:
graft: Next.js 15.5.23 has known critical security advisories. Upgrade to 15.5.24 or later.
Install
npm i @usegraft/sdk-next @usegraft/dbpnpm add @usegraft/sdk-next @usegraft/dbbun add @usegraft/sdk-next @usegraft/dbWrap your Next.js config
Wrap your config with withGraft. It keeps @usegraft/registry out of the
server bundle, because that package reads files from disk at runtime, and it
writes the setting under the name your Next.js version reads. Plain content
reads work without it, but the
MCP route needs it, so add it now:
import { withGraft } from "@usegraft/sdk-next/config";
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// your existing Next.js options
};
export default withGraft(nextConfig);Create the Graft client
Create the client once, in a file only the server imports. Pick the version for your storage engine.
import { openStaticIndex } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-next";
import { collections } from "@/graft.config";
export const graft = createGraft({
index: await openStaticIndex(".graft/index.db"),
collections,
});import { createDb } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-next";
import { collections } from "@/graft.config";
export const { db } = createDb(process.env.DATABASE_URL!);
export const graft = createGraft({ db, collections });The Postgres version also exports db, because the function and MCP routes
below need it.
In the App Router, every read goes through React.cache. If a layout and a
page both read the same document during one request, the index is read once.
The Pages Router reads in one data function per page, so there is nothing to
share.
Show a document
A page reads its document by slug and renders the body with <MdxBody />.
getContent returns null for a slug that does not exist, so send that to
notFound():
import { notFound } from "next/navigation";
import { MdxBody } from "@usegraft/sdk-next";
import { graft } from "@/lib/graft";
// Optional: build every page ahead of time.
export async function generateStaticParams() {
const pages = await graft.listContent("pages");
return pages.map((page) => ({ slug: page.slug }));
}
export default async function Page({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const page = await graft.getContent("pages", slug);
if (!page) notFound();
return (
<article>
<h1>{page.data.title}</h1>
{page.data.tagline && <p>{page.data.tagline}</p>}
<MdxBody source={page.body} />
</article>
);
}page.data is typed from the pages collection in your schema, so a misspelled
field is a compile error, not an empty heading.
Use your own components in Markdown
Pass components to <MdxBody /> to render a tag in your content with your
own React component. This content uses a Callout:
<Callout title="Heads up">Prices change on 1 March.</Callout>And this renders it:
import type { ReactNode } from "react";
import { MdxBody } from "@usegraft/sdk-next";
const components = {
Callout: ({ title, children }: { title?: string; children: ReactNode }) => (
<aside className="callout">
{title && <strong>{title}</strong>}
{children}
</aside>
),
};
export function DocumentBody({ source }: { source: string }) {
return <MdxBody source={source} components={components} />;
}Use the Pages Router
The Pages Router reads content in getStaticProps or getServerSideProps and
renders in a component that also runs in the browser. Two things change from
the App Router: how a body is rendered, and how pages refresh.
| App Router | Pages Router | |
|---|---|---|
| Where you read | Server Components and route handlers | getStaticProps, getServerSideProps and API routes |
| Render a body | <MdxBody source={page.body} /> | prepareMdx in getStaticProps, then <MdxContent code={code} /> |
| Refresh after a change | By tag, with revalidateContent | By path, with res.revalidate |
Show a document
prepareMdx compiles the body on the server, with the same safety rule as
<MdxBody />, and returns a string. <MdxContent /> renders that string, in
the server render and in the browser. Import it from
@usegraft/sdk-next/mdx, which carries no server code, so the page's browser
bundle stays small:
import type { GetStaticPaths, GetStaticProps } from "next";
import { prepareMdx } from "@usegraft/sdk-next";
import { MdxContent } from "@usegraft/sdk-next/mdx";
import { graft } from "@/lib/graft";
interface Props {
title: string;
tagline: string | null;
code: string;
}
export const getStaticPaths: GetStaticPaths = async () => {
const pages = await graft.listContent("pages");
return {
paths: pages.map((page) => ({ params: { slug: page.slug } })),
fallback: "blocking",
};
};
export const getStaticProps: GetStaticProps<Props, { slug: string }> = async ({ params }) => {
const page = await graft.getContent("pages", params?.slug ?? "");
if (!page) return { notFound: true };
return {
props: {
title: page.data.title,
tagline: page.data.tagline ?? null,
code: await prepareMdx(page.body),
},
};
};
export default function Page({ title, tagline, code }: Props) {
return (
<article>
<h1>{title}</h1>
{tagline && <p>{tagline}</p>}
<MdxContent code={code} />
</article>
);
}Props must be JSON, so pass the fields the page shows rather than the whole
document: its updatedAt is a Date, which Next.js refuses to serialize.
Pass components to <MdxContent /> as you would to
<MdxBody />. A body that uses
import, import() or import.meta is refused with
INPUT_VALIDATION_FAILED, even with trust: "full", because the browser has no
bundler to resolve it. Pass the component in components instead. A body that
only mentions an import, in a code span or a fenced block, is prose and renders.
Refresh Pages Router pages
needs PostgresThe Pages Router caches whole pages, not reads, so a change refreshes the
pages that show it, by path. Use this route instead of the App Router's in
step 2 below, and point
GRAFT_REVALIDATE_URL at it as step 3 describes:
import type { NextApiRequest, NextApiResponse } from "next";
const isStrings = (value: unknown): value is string[] =>
Array.isArray(value) && value.every((item) => typeof item === "string");
// The page that shows each changed document. A key is "collection/slug".
function pathFor(key: string): string | null {
const [collection, slug] = key.split("/");
return collection === "pages" && slug ? `/${slug}` : null;
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const secret = process.env.GRAFT_WEBHOOK_SECRET;
if (req.method !== "POST" || !secret || req.headers.authorization !== `Bearer ${secret}`) {
return res.status(401).json({ error: "Unauthorized" });
}
const changes = req.body?.changes;
const keys = [changes?.added, changes?.changed, changes?.removed];
if (!keys.every(isStrings)) {
return res.status(400).json({ error: "Send { branch, changes }." });
}
const paths = keys.flat().flatMap((key) => pathFor(key) ?? []);
await Promise.all(paths.map((path) => res.revalidate(path)));
return res.json({ revalidated: paths });
}Add a line to pathFor for each collection with its own page, and revalidate
any page that lists a collection when a document in it changes. Step 1 below
is not needed: the Pages Router has no cached reads to tag.
Serve functions and MCP from your app
needs PostgresSkip this section unless you need it. Mount these routes when you want to:
- call your typed functions at
POST /api/fn/<name>, or - let remote agents read and write content over MCP at
POST /api/mcp.
Both need the Postgres engine and three more packages:
npm i @usegraft/core @usegraft/auth @usegraft/mcp
Both routes need to know who is calling. This resolver accepts one token from your environment, which is enough to try things out. A dev token never expires, so the resolver ignores it in production. Auth shows how to accept signed tokens from your identity provider.
import { createActorResolver } from "@usegraft/auth";
// A dev token never expires, so it is accepted only in development. An unset
// NODE_ENV counts as production, so a deploy that forgets it stays closed.
const devToken = process.env.NODE_ENV === "development" ? process.env.GRAFT_DEV_TOKEN : undefined;
export const actor = createActorResolver({
devTokens: devToken
? {
[devToken]: {
kind: "human",
id: "owner",
scopes: ["content:write", "submissions:admin"],
},
}
: undefined,
});import { createFunctionsHandler } from "@usegraft/core";
import { functions } from "@/graft.config";
import { actor } from "@/lib/actor";
import { db } from "@/lib/graft";
export const POST = createFunctionsHandler({ db, functions, actor });import { createGraftMcpHandler } from "@usegraft/mcp";
import { collections, functions } from "@/graft.config";
import { actor } from "@/lib/actor";
import { db } from "@/lib/graft";
export const POST = createGraftMcpHandler({
contentDir: "./content",
db,
collections,
functions,
actor,
});A request without a valid token gets a 401. Never mount the MCP route with
allowAnonymous: true on a server that others can reach. For public,
read-only docs, use the docs MCP instead.
Refresh pages when content changes
needs PostgresOn the static engine, content changes ship with a new deploy, so there is
nothing to refresh. On Postgres, content can change while your app is running,
from a local Studio or from an agent. A server that writes to GitHub
(Host Studio for your team) is different: saves are
drafts. Publishing either commits to your production branch or opens a pull
request, and your host rebuilds when the change reaches that branch. A local
Studio refreshes the app after a save that changes content, once the webhook
below (or an onContentChange hook) is set up, and its Publish only commits in
your checkout, which you push yourself. This section makes Next.js refresh only the pages
whose content changed.
It takes two steps. How you cache reads depends on your version. Next.js 16
uses cached functions. Next.js 15 uses unstable_cache. The refresh
route is the same on both. On the Pages Router, use
its own route instead.
Cache each read and tag it with
tagsFor. Use these functions in your pages instead of callinggraftdirectly.Turn on cached functions in the config you wrapped with
withGraft:next.config.ts import { withGraft } from "@usegraft/sdk-next/config"; import type { NextConfig } from "next"; const nextConfig: NextConfig = { // your existing Next.js options cacheComponents: true, }; export default withGraft(nextConfig);Then wrap each read in a
'use cache'function:lib/content.ts import { cacheTag } from "next/cache"; import { tagsFor } from "@usegraft/sdk-next"; import { graft } from "@/lib/graft"; export async function getPage(slug: string) { "use cache"; cacheTag(...tagsFor("main", "pages", slug)); return graft.getContent("pages", slug); } export async function listPages() { "use cache"; cacheTag(...tagsFor("main", "pages")); return graft.listContent("pages"); }Wrap each read in
unstable_cacheand pass the tags:lib/content.ts import { unstable_cache } from "next/cache"; import { tagsFor } from "@usegraft/sdk-next"; import { graft } from "@/lib/graft"; // unstable_cache stores results as JSON, so `updatedAt` comes back as a // string. Turn it back into a Date, so every value matches its type. function revive<T extends { updatedAt: Date }>(doc: T): T { return { ...doc, updatedAt: new Date(doc.updatedAt) }; } export async function getPage(slug: string) { const page = await unstable_cache( () => graft.getContent("pages", slug), ["graft", "pages", slug], { tags: tagsFor("main", "pages", slug) }, )(); return page && revive(page); } const cachedPages = unstable_cache(() => graft.listContent("pages"), ["graft", "pages"], { tags: tagsFor("main", "pages"), }); export async function listPages() { return (await cachedPages()).map(revive); }unstable_cachestores results as JSON, which has no date type, soreviveturns eachupdatedAtback into aDate. Schema fields are not affected:field.datetime()values are ISO strings already.Without this step,
revalidateContenthas nothing to refresh and does nothing.Add a route that refreshes what changed
revalidateContenttakes the list of documents a compile changed and refreshes the matching tags: each changed document, and the collection it is in.app/api/revalidate/route.ts import { revalidateContent, type ChangeSet } from "@usegraft/sdk-next"; const isStrings = (value: unknown): value is string[] => Array.isArray(value) && value.every((item) => typeof item === "string"); function isChangeSet(value: unknown): value is ChangeSet { const v = value as Partial<ChangeSet> | null; return ( isStrings(v?.added) && isStrings(v?.changed) && isStrings(v?.removed) && typeof v?.unchanged === "number" ); } export async function POST(request: Request) { const secret = process.env.GRAFT_WEBHOOK_SECRET; if (!secret || request.headers.get("authorization") !== `Bearer ${secret}`) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } const body = await request.json().catch(() => null); const branch = body?.branch ?? "main"; if (typeof branch !== "string" || !isChangeSet(body?.changes)) { return Response.json({ error: "Send { branch, changes }." }, { status: 400 }); } const tags = revalidateContent(branch, body.changes); return Response.json({ revalidated: tags }); }Add two variables to the
.envGraft reads, or to the environment, wherevergraft serve,graft studio,graft mcp,graft mergeorgraft migrateruns. The secret must match the one the route checks:.env GRAFT_REVALIDATE_URL=https://example.com/api/revalidate GRAFT_WEBHOOK_SECRET=a-long-random-stringThe app's route reads
GRAFT_WEBHOOK_SECRETtoo, so set the same value in the app's runtime environment, such as your host's environment variables. Otherwise the route answers 401 and nothing refreshes.Graft now calls the route after every write that changes content: an agent's
write_contentordelete_content, a local Studio save, create, delete, discard, compile or revert, andgraft merge --applyorgraft migrate --apply. The URL must use https, except on loopback (localhost,127.0.0.1,[::1]).If the route fails, the write still succeeds. The server logs a
REVALIDATE_FAILEDerror, and an agent's result carriesrefresh: { ok: false, fix }, so the agent knows not to retry the write. To refresh those pages, POST the body the server logged with the error to the route. Recompiling does not help: the index already has the change, so a new compile reports those documents as unchanged.
If your app mounts the MCP endpoint itself, skip the webhook. Agent writes run in your app's process, so refresh there:
import { createGraftMcpHandler } from "@usegraft/mcp";
import { revalidateContent } from "@usegraft/sdk-next";
import { collections, functions } from "@/graft.config";
import { actor } from "@/lib/actor";
import { db } from "@/lib/graft";
export const POST = createGraftMcpHandler({
contentDir: "./content",
db,
collections,
functions,
actor,
// An agent's write lands in this app's process, so refresh the cache here.
onContentChange: ({ branch, changes }) => {
revalidateContent(branch, changes);
},
});graft compile never calls the route: a deploy compiles before the new version
is live. To refresh after a deploy, send the compile's output yourself. A shell does not read .env, so the deploy script needs GRAFT_WEBHOOK_SECRET
exported in its environment, which is how most CI systems expose secrets.
The script stops if the compile fails, and --fail makes a refused request
fail the script too:
graft compile --json > changes.json || exit 1
curl --fail -X POST https://example.com/api/revalidate \
-H "Authorization: Bearer $GRAFT_WEBHOOK_SECRET" \
-H "content-type: application/json" \
--data-binary @changes.json
Either way, the route reads a body shaped like this:
{
"branch": "main",
"gitSha": "b8eb719a468be404bae9adca4fbea4d90c642411",
"changes": { "added": ["pages/pricing"], "changed": ["pages/home"], "removed": [], "unchanged": 12 }
}
To refresh inside the same request instead, for example from a Server Action
that saves and then shows the result, use updateContent(branch, changes).
It needs Next.js 16. On 15 it throws FRAMEWORK_VERSION_UNSUPPORTED,
whose fix points you back to revalidateContent.
Run Graft on Next.js 14
Graft does not support Next.js 14, and you should not run it in production. This section is for a project that has to adopt Graft before it can upgrade Next.js. The adapter still runs on 14.2, but CI no longer tests it. The last release tested on 14.2.35 is 1.0.0-beta.8.
What changes from the steps above:
-
Install. The adapter's peer range is
next@^15.0.0 || ^16.0.0. pnpm and bun install anyway and print a peer warning. npm refuses withERESOLVEunless you pass--legacy-peer-deps:npm i @usegraft/sdk-next @usegraft/db --legacy-peer-deps -
Config. Next.js 14 cannot load a TypeScript config. Name the file
next.config.mjs.withGraftwrites the externals setting under the name 14 reads,experimental.serverComponentsExternalPackages:next.config.mjs import { withGraft } from "@usegraft/sdk-next/config"; export default withGraft({ // your existing Next.js options }); -
The static index. Set
"target": "ES2017"intsconfig.json, which the static index version oflib/graft.tsneeds on 14. -
Cached reads. Use the Next.js 15 tab of Refresh pages when content changes:
unstable_cacheandrevalidateContentwork the same on 14.updateContentthrowsFRAMEWORK_VERSION_UNSUPPORTED. -
The Pages Router runs on React 18 there. Reads are not deduped, because React 18 has no
React.cache, and each data function reads once per page anyway.
withGraft prints this each time Next.js loads your config:
graft: Graft does not support Next.js 14. It no longer gets security fixes, and 14.2.35 has critical advisories that will not be fixed on 14. Upgrade to 15.5.24 or 16.3.3 or later. Until you can, see https://graft.page/docs/next#run-graft-on-nextjs-14.
Next steps
- Schema defines the collections and fields your pages read.
- Reading content covers lists, search, and pagination.
- Connecting agents points Cursor or Claude at your project.