Astro

Render Graft content in an Astro site that ships no client JavaScript.

Frameworks7 min read

This guide adds Graft to an Astro project. You read content in a page's frontmatter, so it is fetched at build or request time and the page ships no client JavaScript for it. You can also serve Graft's functions and MCP endpoint from Astro routes.

Before you start, you need an Astro 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 astro makes an Astro 7 site with all of this set up: a home page, a page for each collection and each entry, and MDX bodies rendered with <MdxContent>. Astro 7 needs Node.js 22.23.4 or newer.

Install

pnpm add @usegraft/sdk-astro @usegraft/db
npm i @usegraft/sdk-astro @usegraft/db
bun add @usegraft/sdk-astro @usegraft/db

Create the client once in a server-only module, then import it from frontmatter, endpoints, and middleware. Never from a client island.

Create the Graft client

graft init scaffolds the static index. This docs site is that path:

src/lib/graft.ts
import { openStaticIndex } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-astro";
import { collections } from "../../graft.config";

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

On Postgres:

import { createDb } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-astro";
import { collections } from "../../graft.config";

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

Read a document

src/pages/[slug].astro
---
import { graft } from "../lib/graft";

const page = await graft.getContent("pages", Astro.params.slug!);
---

Astro frontmatter always runs server-side. No other adapter can promise that. Unlike Next.js, Astro has no built-in way to share one read across a request, so reading the same document twice reads the index twice. That is rarely worth worrying about: prerendered pages read once at build time, and a server-rendered page makes only a few reads.

Render MDX bodies

A document's body comes back as its MDX source. MdxContent renders it in the page, with your own Astro components for the ones the body names:

src/pages/[slug].astro
---
import { MdxContent } from "@usegraft/sdk-astro/mdx";
import Callout from "../components/Callout.astro";
import { graft } from "../lib/graft";

const page = await graft.getContent("pages", Astro.params.slug!);
if (!page) return new Response("Not found", { status: 404 });
---

<h1>{page.data.title}</h1>
<MdxContent source={page.body} components={{ Callout }} />

A component gets its attributes as props, and the content between its tags in its default <slot />. If the body names a component that components does not have, its content still renders, without the component around it. MdxContent parses the body in the page's frontmatter, on the server, and sends only HTML to the browser.

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, and it needs the Postgres engine: functions and the audit log they write live in the database. The routes below import the db exported by the Postgres version of src/lib/graft.ts above. The static setup exports no db, so these routes do not work on it.

It also needs three more packages:

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

graftRoute binds a Graft handler to an Astro endpoint. It takes the handler, not a config object: Astro hands over an APIContext, and the handlers want its request.

src/pages/api/fn/[name].ts
import { createFunctionsHandler } from "@usegraft/core";
import { graftRoute } from "@usegraft/sdk-astro";
import { functions } from "../../../graft.config";
import { db } from "../../lib/graft";

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

export const POST = graftRoute(handler);
export const GET = graftRoute(handler); // 405s with Allow and a fix
src/pages/api/mcp.ts
import { createActorResolver } from "@usegraft/auth";
import { createGraftMcpHandler } from "@usegraft/mcp";
import { graftRoute } from "@usegraft/sdk-astro";
import { collections, functions } from "../../graft.config";
import { db } from "../lib/graft";

// 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 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 astro 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. Astro 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-astro";
import { graft } from "../lib/graft";

const slug = Astro.params.slug!;
const page = await graft.getContent("pages", slug);
Astro.response.headers.set("Cache-Tag", tagsFor("main", "pages", 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