TanStack Start

Read Graft content in TanStack Start through server functions.

Frameworks7 min read

This guide adds Graft to a TanStack Start project. You read content through server functions, so the database or index file never reaches the browser, and you can serve Graft's functions and MCP endpoint from server routes.

Before you start, you need a TanStack Start project 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 tanstack-start makes a TanStack Start site with all of this set up: a home page, a page for each collection and each entry, read through server functions, and MDX bodies rendered with <MdxContent>. Its npm start serves the build on Node with srvx.

Install

pnpm add @usegraft/sdk-tanstack-start @usegraft/db
npm i @usegraft/sdk-tanstack-start @usegraft/db
bun add @usegraft/sdk-tanstack-start @usegraft/db

Create the client once in a server-only module, then reach it from server functions and server routes.

Create the Graft client

src/lib/graft.server.ts
import { createDb } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-tanstack-start";
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

src/routes/docs.$slug.tsx
import { createServerFn } from "@tanstack/react-start";
import { graft } from "../lib/graft.server";

const getDoc = createServerFn({ method: "GET" })
  .validator((slug: string) => slug)
  .handler(({ data: slug }) => graft.getContent("docs", slug));

Each call reads the index. If one request reads the same document in several places, cache the result yourself.

Render MDX bodies

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

src/routes/docs.$slug.tsx
import { createFileRoute, notFound } from "@tanstack/react-router";
import { createServerFn } from "@tanstack/react-start";
import { MdxContent } from "@usegraft/sdk-tanstack-start/mdx";
import { prepareMdx } from "@usegraft/sdk-tanstack-start/server";
import { Callout } from "../components/callout";
import { graft } from "../lib/graft.server";

const getDoc = createServerFn({ method: "GET" })
  .validator((slug: string) => slug)
  .handler(async ({ data: slug }) => {
    const doc = await graft.getContent("docs", slug);
    return doc ? { title: doc.data.title, body: prepareMdx(doc.body) } : null;
  });

export const Route = createFileRoute("/docs/$slug")({
  loader: async ({ params }) => {
    const doc = await getDoc({ data: params.slug });
    if (!doc) throw notFound();
    return doc;
  },
  component: Doc,
});

function Doc() {
  const doc = Route.useLoaderData();
  return (
    <article>
      <h1>{doc.title}</h1>
      <MdxContent tree={doc.body} components={{ Callout }} />
    </article>
  );
}

The prepared body is plain data, so the server function returns it and the page renders the same on the server and after a client-side navigation. 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: call prepareMdx only inside a server function or a server route.

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

Copy these mounts as written. The server-route factory name has moved across TanStack Start releases; the handler signature has not.

src/routes/api/fn/$name.ts
import { createServerFileRoute } from "@tanstack/react-start/server";
import { createFunctionsHandler } from "@usegraft/core";
import { graftRoute } from "@usegraft/sdk-tanstack-start";
import { functions } from "../../../graft.config";
import { db } from "../../lib/graft.server";

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

export const ServerRoute = createServerFileRoute("/api/fn/$name").methods({
  POST: graftRoute(handler),
  GET: graftRoute(handler), // 405s with Allow and a fix
});
src/routes/api/mcp.ts
import { createActorResolver } from "@usegraft/auth";
import { createServerFileRoute } from "@tanstack/react-start/server";
import { createGraftMcpHandler } from "@usegraft/mcp";
import { graftRoute } from "@usegraft/sdk-tanstack-start";
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 ServerRoute = createServerFileRoute("/api/mcp").methods({
  POST: 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.

The parameter is typed structurally as { request: Request }, so this package needs no @tanstack/react-start dependency.

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. TanStack Start 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 { createServerFn } from "@tanstack/react-start";
import { setResponseHeader } from "@tanstack/react-start/server";
import { tagsFor } from "@usegraft/sdk-tanstack-start";
import { graft } from "../lib/graft.server";

const getDoc = createServerFn({ method: "GET" })
  .validator((slug: string) => slug)
  .handler(({ data: slug }) => {
    setResponseHeader("Cache-Tag", tagsFor("main", "docs", slug).join(","));
    return graft.getContent("docs", slug);
  });

The header goes on whichever response ran the function. On a full page load that is the page's HTML. On client-side navigation, the browser calls the server function directly, so it is that GET response. Let your CDN cache both: they carry the same tags, so one purge refreshes both.

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