React Router

Read Graft content in React Router framework mode.

Frameworks7 min read

This guide adds Graft to a React Router app in framework mode. You read content in route loaders on the server, and you can serve Graft's functions and MCP endpoint from resource routes.

Before you start, you need a React Router app in framework mode and a graft.config.ts with compiled content. If you do not have those yet, run through Getting started first.

Starting from nothing? npm create graft@latest my-site -- --framework react-router makes a React Router 8 site with all of this set up: a home page, a page for each collection and each entry, and MDX bodies rendered with <MdxContent>. React Router 8 needs Node.js 22.22 or newer.

Install

pnpm add @usegraft/sdk-react-router @usegraft/db
npm i @usegraft/sdk-react-router @usegraft/db
bun add @usegraft/sdk-react-router @usegraft/db

For framework mode, which is where React Router runs loaders and actions on a server. Create the client once in a .server.ts module.

Create the Graft client

app/lib/graft.server.ts
import { createDb } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-react-router";
import { collections } from "../../graft.config";

export const db = createDb(process.env.DATABASE_URL!).db;
export const graft = createGraft({ db, collections });

Static index instead of Postgres:

import { openStaticIndex } from "@usegraft/db";

export const graft = createGraft({
  index: await openStaticIndex(".graft/index.db"),
  collections,
});

Read a document

app/routes/docs.$slug.tsx
import { graft } from "../lib/graft.server";
import type { Route } from "./+types/docs.$slug";

export async function loader({ params }: Route.LoaderArgs) {
  return { doc: await graft.getContent("docs", params.slug) };
}

loader and action run on the server and React Router strips them from the browser bundle. The .server.ts name is belt and braces on top of that: it turns a stray client import into a build error rather than a database URL in a bundle.

To read content in the browser (a search box, an editor preview), use the React adapter.

Render MDX bodies

A document's body comes back as its MDX source. Prepare it in the loader with prepareMdx, then render the result with MdxContent and your own React components:

app/routes/docs.$slug.tsx
import { data } from "react-router";
import { MdxContent } from "@usegraft/sdk-react-router/mdx";
import { prepareMdx } from "@usegraft/sdk-react-router/server";
import { Callout } from "../components/callout";
import { graft } from "../lib/graft.server";
import type { Route } from "./+types/docs.$slug";

export async function loader({ params }: Route.LoaderArgs) {
  const doc = await graft.getContent("docs", params.slug);
  if (!doc) throw data("Not found", { status: 404 });
  return { title: doc.data.title, body: prepareMdx(doc.body) };
}

export default function Doc({ loaderData }: Route.ComponentProps) {
  return (
    <article>
      <h1>{loaderData.title}</h1>
      <MdxContent tree={loaderData.body} components={{ Callout }} />
    </article>
  );
}

The prepared body is plain data, so it reaches the page in the loader's data and renders the same on the server and when the page hydrates. A component gets its attributes as props and the content between its tags as children. If the body names a component that components does not have, its content still renders, without the component around it. The Markdown parser stays on the server: import @usegraft/sdk-react-router/server only from loaders, actions and .server.ts modules.

The body is never evaluated, which makes this renderer stricter than MdxBody in Next.js: {expressions}, import, export and spread attributes are refused with INPUT_VALIDATION_FAILED under every trust level, along with <script>-like elements, on… handlers and innerHTML-style attributes. graft compile refuses the same constructs unless the project sets mdxTrust = "full", so a body that compiled meets this only with full trust, or when it reached the index another way, such as a direct database write. Under restricted trust, a script URL is removed from any link, image or other source, and the rest of the body renders: a link keeps its text. Pass trust: "full" to keep every URL. See MDX safety.

Serve functions and MCP from your app

This step is optional: it needs the Postgres engine and three more packages:

npm i @usegraft/core @usegraft/auth @usegraft/mcp

graftRoute binds a Graft handler to a resource route. That is a route module with no default export, whose loader and action return raw Responses.

app/routes/api.fn.$name.ts
import { createFunctionsHandler } from "@usegraft/core";
import { graftRoute } from "@usegraft/sdk-react-router";
import { functions } from "../../graft.config";
import { db } from "../lib/graft.server"; // export the same db you passed to createGraft

const handler = createFunctionsHandler({ db, functions });

export const action = graftRoute(handler); // POST
export const loader = graftRoute(handler); // GET, which 405s with Allow and a fix
app/routes/api.mcp.ts
import { createActorResolver } from "@usegraft/auth";
import { createGraftMcpHandler } from "@usegraft/mcp";
import { graftRoute } from "@usegraft/sdk-react-router";
import { collections, functions } from "../../graft.config";
import { db } from "../lib/graft.server";

// 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;

const actor = createActorResolver({
  issuers: (process.env.GRAFT_TRUSTED_ISSUERS ?? "")
    .split(/[,\s]+/)
    .filter(Boolean)
    .map((issuer) => ({ issuer })),
  devTokens: devToken
    ? {
        [devToken]: {
          kind: "human",
          id: "owner",
          scopes: ["content:write"],
        },
      }
    : undefined,
});

export const action = graftRoute(
  createGraftMcpHandler({
    contentDir: "./content",
    db,
    collections,
    functions,
    actor,
  }),
);

This endpoint serves content writes and asset uploads. JWT verification runs only when issuers is passed; the library does not read GRAFT_TRUSTED_ISSUERS (graft serve does). See Auth. Unauthenticated callers get 401. allowAnonymous: true is only for a loopback local server. Never anything reachable from a network. A public docs surface is createDocsMcpHandler, which has no write tools and no anonymous opt-in.

Register them the way you register any route:

app/routes.ts
import { route, type RouteConfig } from "@react-router/dev/routes";

export default [
  route("api/fn/:name", "routes/api.fn.$name.ts"),
  route("api/mcp", "routes/api.mcp.ts"),
] satisfies RouteConfig;

Refresh pages when content changes

needs Postgres

On 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. React Router has no tag-based data cache, so let your CDN cache pages and purge only the ones whose content changed.

First, send each page with a header that lists the content it read. tagsFor builds that list:

import { tagsFor } from "@usegraft/sdk-react-router";
import type { Route } from "./+types/docs.$slug";

export function headers({ params }: Route.HeadersArgs) {
  return { "Cache-Tag": tagsFor("main", "docs", params.slug).join(",") };
}

Then, when content changes, purge those tags at your CDN. tagsForChanges(branch, changes) turns a change list into the tags to purge: each changed document, and the collection it is in. Graft does not purge your CDN itself. Add a route that reads branch and changes from a POST body, checks a bearer secret, and purges the tags tagsForChanges returns.

Then point Graft at the route. Add two variables to the .env Graft reads, or to the environment, wherever graft serve, graft studio, graft mcp, graft merge or graft migrate runs. The secret must match the one the route checks:

.env
GRAFT_REVALIDATE_URL=https://example.com/api/revalidate
GRAFT_WEBHOOK_SECRET=a-long-random-string

The app's route reads GRAFT_WEBHOOK_SECRET too, 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_content or delete_content, a local Studio save, create, delete, discard, compile or revert, and graft merge --apply or graft migrate --apply. If the route fails, the write still succeeds, and the server logs a REVALIDATE_FAILED error with the body to resend. Recompiling does not resend it: a new compile reports those documents as unchanged. If your app mounts the MCP endpoint itself, pass onContentChange to createGraftMcpHandler and purge there instead.

graft compile never calls the route: a deploy compiles before the new version is live. To purge 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

Cache-Tag is the header Cloudflare reads, with tags separated by commas. Fastly reads Surrogate-Key, with tags separated by spaces. Use the header your CDN expects.

Next steps