SvelteKit
Read Graft content in SvelteKit server load functions.
This guide adds Graft to a SvelteKit project. You read content in server
load functions, render it in your pages, and can serve Graft's functions and
MCP endpoint from +server.ts routes.
Before you start, you need a SvelteKit 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 sveltekit
makes a SvelteKit 3 site with all of this set up: a home page, a page for each
collection and each entry, and MDX bodies rendered with <MdxContent>.
Install
pnpm add @usegraft/sdk-sveltekit @usegraft/dbnpm i @usegraft/sdk-sveltekit @usegraft/dbbun add @usegraft/sdk-sveltekit @usegraft/dbCreate the client in $lib/server/, so SvelteKit's server-only enforcement
guards it. The client holds a database connection and must never reach the browser.
Create the Graft client
import { DATABASE_URL } from "$env/static/private";
import { createDb } from "@usegraft/db";
import { createGraft } from "@usegraft/sdk-sveltekit";
import { collections } from "../../../graft.config";
export const db = createDb(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
import { error } from "@sveltejs/kit";
import { graft } from "$lib/server/graft";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ params }) => {
const page = await graft.getContent("pages", params.slug);
if (!page) error(404);
return { page };
};Render MDX with Svelte components
A document's body is its MDX source as written. Turn it into a tree with
prepareMdx in the same load, and render the tree with <MdxContent>:
import { error } from "@sveltejs/kit";
import { prepareMdx } from "@usegraft/sdk-sveltekit/server";
import { graft } from "$lib/server/graft";
import type { PageServerLoad } from "./$types";
export const load: PageServerLoad = async ({ params }) => {
const page = await graft.getContent("pages", params.slug);
if (!page) error(404);
return { page, body: prepareMdx(page.body) };
};<script lang="ts">
import { MdxContent } from "@usegraft/sdk-sveltekit/mdx";
import Callout from "../../lib/Callout.svelte";
import type { PageProps } from "./$types";
let { data }: PageProps = $props();
</script>
<h1>{data.page.data.title}</h1>
<MdxContent tree={data.body} components={{ Callout }} />The tree is plain data, so it reaches the page in SvelteKit's own page data
and renders the same on the server and when the page hydrates. A component
receives the content between its tags as its children snippet. If the body
names a component that components does not have, its content still renders,
without the component around it. The parser stays on the server:
@usegraft/sdk-sveltekit/server is for load functions and +server.ts
routes only.
Svelte has no JSX runtime, so this renderer never evaluates the body. That
makes it 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. A refused body makes prepareMdx throw, and
the load answers 500 unless you catch it. graft compile refuses the same
constructs unless the project sets mdxTrust = "full", so this only comes up
with full trust. Links with a script URL are dropped unless you call
prepareMdx(page.body, { trust: "full" }). 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
import { createFunctionsHandler } from "@usegraft/core";
import { graftRoute } from "@usegraft/sdk-sveltekit";
import { functions } from "../../../../graft.config";
import { db } from "$lib/server/graft";
const handler = createFunctionsHandler({ db, functions });
export const POST = graftRoute(handler);
export const GET = graftRoute(handler); // 405s with Allow and a fiximport { createActorResolver } from "@usegraft/auth";
import { createGraftMcpHandler } from "@usegraft/mcp";
import { graftRoute } from "@usegraft/sdk-sveltekit";
import { collections, functions } from "../../../../graft.config";
import { db } from "$lib/server/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 @sveltejs/kit dependency.
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. SvelteKit 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-sveltekit";
export const load: PageServerLoad = async ({ params, setHeaders }) => {
const page = await graft.getContent("pages", params.slug);
setHeaders({ "Cache-Tag": tagsFor("main", "pages", params.slug).join(",") });
return { page };
};
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:
GRAFT_REVALIDATE_URL=https://example.com/api/revalidate
GRAFT_WEBHOOK_SECRET=a-long-random-stringThe 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.
Supported versions
The adapter supports SvelteKit 2 and SvelteKit 3. SvelteKit 3 needs Node 22.17
or newer. CI builds a real SvelteKit 2 app and a real SvelteKit 3 app on every
pull request, type-checks the static-index client, the reads and graftRoute
against each one, serves the build, and drives it in Chromium.
graftRoute takes any event with a request, so the adapter does not depend
on @sveltejs/kit and needs no change between majors.
Next steps
- Reading content covers list and search reads.
- SDK reference compares route mounts across frameworks.
- Connecting agents points an agent at your project.