Visual Editing with Astro
Configure Sanity’s Presentation Tool, draft mode, and visual editing overlays to work with an Astro 7 server-rendered frontend.
This guide walks through the specific wiring that makes Sanity's visual editing work with an Astro application. Compared to the Astro blog guide's setup, it takes more code: you write your own draft mode routes and query helper. In return you get automatic content refresh on edit, perspective switching, and full control over how draft content is fetched.
Looking for a simpler setup?
If you’re looking for a more drop-in, but less featured visual editing implementation, check out the Building a blog with Sanity and Astro guide.
By the end, editors will be able to open the Presentation Tool in the studio, see the frontend in a live preview, click on any text element to jump to the corresponding field, and see changes reflected after each edit.
What you'll set up:
- The
@sanity/astrointegration, which provides a pre-configured Sanity client with Content Source Map encoding. - A custom
loadQueryfunction that switches between published and draft content based on cookies. - Cookie-based draft mode routes to toggle between published and draft content.
- The Presentation Tool with document-to-URL mapping.
- The
<VisualEditing />component from@sanity/astro, which draws click-to-edit overlays, keeps the Presentation Tool in sync with the page, and refreshes the page after each edit. It doesn't need React.
The guide assumes you already have document types defined in your Studio and pages that render them. The focus is purely on the integration layer: the files and configuration that connect the two apps.
Astro and the Live Content API
Next.js integrations use the Live Content API (defineLive / <SanityLive />) for real-time re-rendering without page reloads. Astro doesn't have a direct equivalent for visual editing. @sanity/astro 4.0.0 added an experimental, opt-in experimental_live option that generates live loaders for Astro content collections, but it doesn't re-render the page as content changes. Instead, when an editor changes a field, the <VisualEditing /> component reloads the page to fetch fresh content from the server.
In @sanity/astro 4.0.0 and later, you can opt in to an experimental refresh that updates the page in place instead of reloading it. See Refresh the preview without reloading the page.
Prerequisites
- Node.js 22.12 or later. Later Astro 7 releases require a newer Node.js 22 patch release, so check the
enginesfield of the Astro version you install. - Astro 7 with
output: "server". Visual editing requires server-side rendering because draft mode depends on per-request cookie checking. Static output mode will not work. @sanity/astrov4.0.0 or later and@astrojs/nodev11+.- A Sanity project with a dataset. Create one if you don't have one.
- An API token with Viewer permissions for that project. Create one under API → Tokens in your project settings.
http://localhost:4321added as a CORS origin with Allow credentials checked.
You can create a basic Astro app by following the Astro quickstart. Then, navigate to the Astro project’s frontend and make sure you have the latest packages by running the following command:
npm install @sanity/astro @astrojs/node @sanity/client @sanity/image-url @sanity/preview-url-secret @portabletext/astro @portabletext/types groqpnpm add @sanity/astro @astrojs/node @sanity/client @sanity/image-url @sanity/preview-url-secret @portabletext/astro @portabletext/types groqyarn add @sanity/astro @astrojs/node @sanity/client @sanity/image-url @sanity/preview-url-secret @portabletext/astro @portabletext/types groqbun add @sanity/astro @astrojs/node @sanity/client @sanity/image-url @sanity/preview-url-secret @portabletext/astro @portabletext/types groqThis example keeps the studio and the Astro app in separate folders. Create a new studio by running the following command in your project root:
npm create sanity@latest -- --dataset production --template clean --typescript --output-path studio
cd studiopnpm create sanity@latest --dataset production --template clean --typescript --output-path studio
cd studioyarn create sanity@latest --dataset production --template clean --typescript --output-path studio
cd studiobun create sanity@latest --dataset production --template clean --typescript --output-path studio
cd studioHow the pieces fit together
Before diving into the code, here's what happens at runtime when an editor opens the Presentation Tool:
- The studio loads the Astro frontend inside an iframe. The URL it loads comes from the
initialfield in the Presentation Tool configuration. - The studio hits the draft mode enable route on the frontend (
/api/draft-mode/enable). This sets a cookie that activates draft mode in the iframe session. - With draft mode active,
loadQueryreturns strings with invisible characters embedded in them. These characters are Content Source Maps (called "stega") that encode which document and field each string came from, along with the studio URL. - The
<VisualEditing />component (enabled only during draft mode) reads those encoded strings from the DOM and draws click-to-edit overlays on every text element. - When an editor clicks an overlay, the studio navigates to that document and field.
- When an editor changes a field,
<VisualEditing />reloads the page. The page re-fetches from the server with the updated draft content.
Contracts between the two apps
If you change one side, check the other.
- The studio's
previewMode.enablepath (/api/draft-mode/enable) must match an actual API route in the Astro app. - The URLs returned by
resolve.ts(for example,/post/${slug}) must match actual page routes infrontend/src/pages/. - The
stega.studioUrlin the@sanity/astrointegration config must point to the running studio. - The Sanity project must have the frontend's origin in its CORS settings with Allow credentials enabled.
Environment variables
Set up environment variables for your Astro app (frontend) and Studio (studio).
PUBLIC_SANITY_PROJECT_ID=<your-project-id>
PUBLIC_SANITY_DATASET=<your-dataset>
SANITY_API_READ_TOKEN=YOUR_VIEWER_TOKENSANITY_STUDIO_PROJECT_ID=<your-project-id>
SANITY_STUDIO_DATASET=<your-dataset>
SANITY_STUDIO_PREVIEW_URL=http://localhost:4321PUBLIC_SANITY_PROJECT_ID and PUBLIC_SANITY_DATASET are public because the @sanity/astro integration needs them in astro.config.mjs (loaded via Vite's loadEnv).
SANITY_API_READ_TOKEN is server-only and never exposed to the client bundle. It's passed to loadQuery only when draft mode is active, to authenticate requests for draft content.
Note that Studio environment variables should always start with SANITY_STUDIO. However, it’s safe to hard-code the projectId, dataset, and preview URL in sanity.config.ts if you prefer.
Studio setup
These files live in studio/. If you're setting up a new studio from scratch, these examples use a blog schema with post, author, and category document types.
Presentation Tool configuration
The Presentation Tool is a Studio plugin that renders your frontend inside an iframe and enables the visual editing workflow. Configure it in sanity.config.ts:
import { defineConfig } from "sanity";
import { structureTool } from "sanity/structure";
import { presentationTool } from "sanity/presentation";
import { schema } from "./schemaTypes";
import { resolve } from "./lib/resolve";
export default defineConfig({
projectId: process.env.SANITY_STUDIO_PROJECT_ID || '<your-project-id>',
dataset: process.env.SANITY_STUDIO_DATASET || 'production',
plugins: [
structureTool(),
presentationTool({
resolve,
previewUrl: {
initial:
process.env.SANITY_STUDIO_PREVIEW_URL || "http://localhost:4321",
previewMode: {
enable: "/api/draft-mode/enable",
},
},
}),
],
schema,
});The important fields here:
- resolve: This defines the document location resolver. You'll set this up in the next section.
- previewUrl.initial: The full URL of the Astro app. The Presentation Tool loads this in the iframe. When the studio and frontend are separate apps (as they are here), this is required.
- previewUrl.previewMode.enable: The path (relative to
initial) that the studio calls to activate draft mode. The studio makes a GET request tohttp://localhost:4321/api/draft-mode/enablewith authentication parameters. This is what activates draft mode so the frontend returns draft content with stega encoding.
Document locations
Document locations tell the Presentation Tool which frontend URLs correspond to which document types. This powers two things: when you select a document in the studio, the iframe navigates to the right page; and documents show location badges linking to their frontend URLs.
import { defineLocations } from "sanity/presentation";
import type { PresentationPluginOptions } from "sanity/presentation";
export const resolve: PresentationPluginOptions["resolve"] = {
locations: {
// The key is the document type name from your schema
post: defineLocations({
select: {
title: "title",
slug: "slug.current",
},
resolve: (doc) => ({
locations: [
{
title: doc?.title || "Untitled",
href: `/post/${doc?.slug}`,
},
{
title: "Home",
href: "/",
},
],
}),
}),
},
};select uses GROQ-like field paths to pull data from the document. resolve receives that data and returns an array of {title, href} objects. The first location is treated as the primary one. You can add multiple locations if a document appears on several pages (for example, a post appears on its own page and on the posts index).
CORS
The Sanity project needs http://localhost:4321 added as a CORS origin with Allow credentials enabled. If you already added this in the prerequisites, you're set. If not, add it in your project settings at sanity.io/manage under API → CORS Origins, or add it with the CLI:
npx sanity cors add http://localhost:4321 --credentialspnpm dlx sanity cors add http://localhost:4321 --credentialsyarn dlx sanity cors add http://localhost:4321 --credentialsbunx sanity cors add http://localhost:4321 --credentialsFor production, you'd add your deployed frontend URL as well.
Astro setup
These files live in frontend/. The structure follows a standard Astro project with server-side rendering enabled.
Astro configuration
import { defineConfig } from "astro/config";
import sanity from "@sanity/astro";
import node from "@astrojs/node";
import { loadEnv } from "vite";
const { PUBLIC_SANITY_PROJECT_ID, PUBLIC_SANITY_DATASET } = loadEnv(
process.env.NODE_ENV,
process.cwd(),
"",
);
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
integrations: [
sanity({
projectId: PUBLIC_SANITY_PROJECT_ID,
dataset: PUBLIC_SANITY_DATASET,
useCdn: false,
apiVersion: "2026-03-01",
stega: {
studioUrl: "http://localhost:3333",
},
}),
],
vite: {
optimizeDeps: {
include: [
"react/compiler-runtime",
"react/jsx-runtime",
"lodash/isObject.js",
"lodash/groupBy.js",
"lodash/keyBy.js",
"lodash/partition.js",
"lodash/sortedIndex.js",
],
},
},
});Each part of this configuration does the following:
- output: "server": Enables server-side rendering. This is required because draft mode depends on reading cookies from each incoming request to decide whether to return published or draft content. Static builds can't do this.
- adapter: node({ mode: "standalone" }): The Node.js adapter runs the Astro app as a standalone server. You could also use other adapters (Vercel, Cloudflare, etc.) for deployment.
- sanity({ ... }): The
@sanity/astrointegration configures a Sanity client that's available throughout your app via thesanity:clientvirtual module. No manualcreateClientcall needed. - stega.studioUrl: When draft mode is active and stega encoding is enabled, this URL is embedded in the invisible characters so the overlay knows where to send the editor when they click. For production, point this to your deployed Studio URL.
- useCdn: false: Disabled so draft content is always fresh. In a production setup, you might conditionally enable it for published content.
- vite.optimizeDeps.include: Pre-bundles CommonJS modules that the Visual Editing overlays import. Without these entries, the overlays fail to start in the dev server, and the browser console shows an error such as
does not provide an export named 'default'. Production builds don't need them. Keep thereact/*entries too. Your pages don't use React, and you don't need the React integration for Astro, but the overlay script itself is built with React, which npm installs as a peer dependency of @sanity/astro. To run the overlays on the self-contained@sanity/visual-editing-standalonebuild instead, install that package and setvisualEditingStandalone: truein thesanity()integration options. The dev server still needs the sameoptimizeDeps.includeentries with that option.
The Sanity client
Unlike Next.js where you create the client manually with createClient, the @sanity/astro integration provides a pre-configured client via a virtual module. To use it, add the type references in your env file:
/// <reference types="astro/client" />
/// <reference types="@sanity/astro/module" />The second line tells TypeScript about the sanity:client virtual module, which you can then import anywhere:
import { sanityClient } from "sanity:client";The client is automatically configured with the projectId, dataset, apiVersion, and stega settings from astro.config.mjs.
Draft mode helper
Astro doesn't have a dedicated draftMode like Next.js, so this guide implements draft mode with cookies. This small helper reads the draft mode state from Astro.cookies:
import type { AstroCookies } from "astro";
import {perspectiveCookieName} from "@sanity/preview-url-secret/constants";
export function getDraftModeProps(cookies: AstroCookies) {
return {
perspectiveCookie: cookies.get(perspectiveCookieName)?.value ?? undefined,
};
}This reads a client-writable cookie that the draft mode enable route sets. It stores the perspective the editor had selected when the Presentation Tool enabled draft mode (for example, a specific content release). To keep it in sync when the editor switches perspectives afterward, see Follow perspective changes from the studio.
Fetching data
This is the central piece that replaces Next.js's defineLive / sanityFetch. It's a custom loadQuery function that handles perspective switching, stega encoding, and source maps based on whether draft mode is active:
import type { ClientPerspective, QueryParams } from "@sanity/client";
import { sanityClient } from "sanity:client";
const token = import.meta.env.SANITY_API_READ_TOKEN;
function parsePerspective(
raw: string | undefined,
): ClientPerspective | undefined {
if (!raw) return undefined;
const decoded = decodeURIComponent(raw);
if (decoded.startsWith("[")) {
try {
return JSON.parse(decoded) as ClientPerspective;
} catch {
return undefined;
}
}
return decoded as ClientPerspective;
}
export async function loadQuery<QueryResponse>({
query,
params,
perspectiveCookie = undefined,
}: {
query: string;
params?: QueryParams;
perspectiveCookie?: string | undefined;
}) {
const draftMode = perspectiveCookie ? true : false;
if (draftMode && !token) {
throw new Error(
"The `SANITY_API_READ_TOKEN` environment variable is required during Visual Editing.",
);
}
const perspective: ClientPerspective = draftMode
? (parsePerspective(perspectiveCookie) ?? "drafts")
: "published";
const { result, resultSourceMap } = await sanityClient.fetch<QueryResponse>(
query,
params ?? {},
{
filterResponse: false,
perspective,
resultSourceMap: draftMode ? "withKeyArraySelector" : false,
stega: draftMode,
...(draftMode ? { token } : {}),
},
);
return {
data: result,
sourceMap: resultSourceMap,
perspective,
};
}The function handles two modes:
- Published mode (default): Uses the
"published"perspective, no stega encoding, no source maps, no token. This is what visitors see. - Draft mode: Uses the
"drafts"perspective (or a custom perspective from the cookie for Content Releases), enables stega encoding and source maps withwithKeyArraySelector, and authenticates with the API token.
The parsePerspective helper deserializes the perspective cookie, which can be either a simple string like "drafts" or a JSON-encoded array for Content Release stacks. This exact implementation isn’t required, but works with the rest of the code.
The filterResponse: false option tells the client to return both the query result and the source map, rather than just the result.
GROQ queries
Queries are defined using defineQuery from the groq package, which enables TypeGen to generate result types. If you don’t have it already, add groq to your project dependencies:
import { defineQuery } from "groq";
export const POSTS_QUERY = defineQuery(
`*[_type == "post" && defined(slug.current)] | order(publishedAt desc) {
_id,
title,
"slug": slug.current,
publishedAt
}`,
);
export const POST_QUERY = defineQuery(
`*[_type == "post" && slug.current == $slug][0]{
_id,
_type,
title,
"slug": slug.current,
publishedAt,
mainImage {
asset->{ _id, url, metadata { lqip, dimensions } },
alt,
hotspot,
crop
},
body[]{
...,
_type == "image" => {
...,
asset->{ _id, url, metadata { lqip, dimensions } },
alt
}
},
author->{ _id, name, "slug": slug.current },
categories[]->{ _id, title }
}`,
);With TypeGen configured in the studio's sanity.cli.ts, running sanity typegen generate produces typed result types (POSTS_QUERY_RESULT, POST_QUERY_RESULT) in frontend/sanity.types.ts. These are used as generics with loadQuery<POST_QUERY_RESULT>() for type-safe data access.
The layout
The shared layout conditionally renders visual editing components when draft mode is active:
---
import { VisualEditing } from "@sanity/astro/visual-editing";
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
import DisableDraftMode from "../components/DisableDraftMode.astro";
const draftMode = Astro.cookies.has(perspectiveCookieName);
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>Astro Basics</title>
</head>
<body>
<slot />
<VisualEditing enabled={draftMode} />
{draftMode && <DisableDraftMode />}
</body>
</html>Two components are doing the visual editing work here:
<VisualEditing />: from@sanity/astro/visual-editing. It scans the DOM for stega-encoded strings, decodes the Content Source Map data embedded in them (document ID, field path, studio URL), and draws transparent overlays on top of each element. It also keeps the Presentation Tool's URL in sync with the page and reloads the page when content changes. Theenabledprop turns it on only in draft mode.<DisableDraftMode />: renders a floating link to exit draft mode, but only when the user is viewing the frontend directly (not inside the Presentation Tool's iframe).
Both are .astro components, so the frontend needs no React integration. <VisualEditing /> only loads its overlay script in the browser when enabled is true.
The Astro.cookies.has(perspectiveCookieName) check is the gate. Outside of draft mode, the page renders clean published content with no overlays and no invisible characters.
The VisualEditing component
In Next.js, next-sanity provides a <VisualEditing /> component. In Astro, @sanity/astro provides one too, exported from @sanity/astro/visual-editing. It renders as a plain <script>, so it works on sites built only from .astro files.
The component has three responsibilities:
- Overlays: draws click-to-edit overlays on every element that contains stega-encoded text.
- History synchronization: keeps the Presentation Tool's URL bar in sync with the page. When the editor selects a document that resolves to a different URL, the component navigates there with a full page load, because Astro pages aren't a single-page app.
- Content refresh: reloads the page when the studio reports a content change, so the server renders the updated draft content.
It accepts these props:
- enabled: renders the component only when
true. The layout passes the draft mode check. - zIndex: optional. The
z-indexof the overlay elements. - keepStegaOnCopy: optional. By default, the component strips stega encoding from text users copy from the page. Pass
keepStegaOnCopyto leave the encoding in copied text. - experimental_refreshStrategy: optional and experimental. How the page catches up with an edit. Defaults to
'reload'. See Refresh the preview without reloading the page.
Refresh the preview without reloading the page
By default, <VisualEditing /> reloads the page on every refresh, which resets scroll position, focus, and form state. In @sanity/astro 4.0.0 and later, set experimental_refreshStrategy="in-place" to update the page without reloading it:
<VisualEditing enabled={draftMode} experimental_refreshStrategy="in-place" />Edits then reach the page in two steps:
- Instant text: stega-encoded text from the changed document updates as soon as the change arrives, before any request to your server. Text your page transformed (truncated, formatted, or combined from several fields) waits for the next step.
- In-place morph: half a second after the last change, the component fetches the current URL and patches the page to match the fresh server HTML. Scroll position, focus, form state, and the Presentation Tool connection survive because the page never navigates.
If the fetch fails, or the fresh HTML adds a <script> the page doesn't have yet, the component falls back to a full page reload.
In-place refresh removes injected DOM
The morph removes DOM that third-party scripts injected, such as cookie banners, chat widgets, and analytics snippets, and those scripts don't run again until the next full page load. Add Astro's transition:persist attribute to elements you control, or keep the default 'reload' strategy on sites that depend on these scripts.
The option is experimental. While it carries the experimental_ prefix, its name and behavior can change in a minor release.
Draft mode routes
These two routes are the bridge between the studio and the frontend.
Enable route:
import type { APIRoute } from "astro";
import { validatePreviewUrl } from "@sanity/preview-url-secret";
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
import { sanityClient } from "sanity:client";
export const GET: APIRoute = async ({ request, cookies, redirect }) => {
const token = import.meta.env.SANITY_API_READ_TOKEN;
if (!token) {
return new Response("Server misconfigured: missing read token", {
status: 500,
});
}
const clientWithToken = sanityClient.withConfig({ token });
const { isValid, redirectTo = "/", studioPreviewPerspective } = await validatePreviewUrl(
clientWithToken,
request.url,
);
if (!isValid) {
return new Response("Invalid secret", { status: 401 });
}
// Safari blocks third-party cookies that aren't partitioned. When the
// Presentation Tool loads this route inside a cross-site iframe, add the
// CHIPS Partitioned attribute so Safari stores the cookie under the Studio's
// partition. Top-level requests stay unpartitioned, so the disable route can
// still clear them.
const partitioned =
request.headers.get("sec-fetch-dest") === "iframe" &&
request.headers.get("sec-fetch-site") === "cross-site";
cookies.set(perspectiveCookieName, studioPreviewPerspective ?? "drafts", {
httpOnly: false,
sameSite: "none",
secure: true,
path: "/",
partitioned,
});
return redirect(redirectTo, 307);
};When an editor opens the Presentation Tool, the studio makes a GET request to this route with authentication parameters. validatePreviewUrl (from @sanity/preview-url-secret) handles the handshake: it verifies the request came from a legitimate studio session by checking a shared secret stored in the dataset. If the request is valid, the route sets the cookie to the perspective value and redirects to the requested page.
The cookie settings are important:
- httpOnly:
falseallows client-side JavaScript to read and modify the cookie. Confirm this is what you want in your implementation. For this guide, it enables the perspective-switching mechanism to function. - sameSite: "none": Required because the request comes from the studio (a different origin) loading the frontend in an iframe.
- secure:
truerequired whensameSiteis"none". - partitioned: Adds the CHIPS
Partitionedattribute when the request comes from a cross-site iframe. Safari blocks third-party cookies that aren't partitioned, so without it the cookie is dropped and draft mode never activates. Top-level requests stay unpartitioned, because a partitioned cookie can't be cleared by a same-site request.
In Next.js, defineEnableDraftMode from next-sanity/draft-mode wraps this logic. In Astro, call validatePreviewUrl directly.
Disable route:
import type { APIRoute } from "astro";
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
export const GET: APIRoute = async () => {
// A partitioned cookie is only cleared by an expiring cookie that carries the
// same Partitioned attribute, and cookies.delete() emits a single Set-Cookie
// header per cookie name. Expire both variants directly instead, since either
// may have been set depending on the browser and context.
const expired = [
`${perspectiveCookieName}=`,
"Path=/",
"Secure",
"SameSite=None",
"Max-Age=0",
];
const headers = new Headers();
headers.append("Set-Cookie", expired.join("; "));
headers.append("Set-Cookie", [...expired, "Partitioned"].join("; "));
headers.set("Location", "/");
return new Response(null, { status: 307, headers });
};This clears the cookie and redirects to the homepage. The Disable Draft Mode link in DisableDraftMode.astro points to this route.
The Disable Draft Mode link
<a id="disable-draft-mode" href="/api/draft-mode/disable" hidden>
Disable Draft Mode
</a>
<script>
// Show the button only when the page isn't framed by the Presentation Tool.
if (window.self === window.top) {
document.getElementById("disable-draft-mode")?.removeAttribute("hidden");
}
</script>
<style>
#disable-draft-mode {
position: fixed;
bottom: 1rem;
right: 1rem;
z-index: 50;
padding: 0.5rem 1rem;
border-radius: 9999px;
background-color: #101112;
color: #fff;
font-size: 0.875rem;
text-decoration: none;
}
#disable-draft-mode[hidden] {
display: none;
}
</style>This component renders a floating link to exit draft mode, but only when the user is viewing the frontend directly in a browser tab (not inside the Presentation Tool's iframe). Inside the Presentation Tool, the studio controls draft mode, so the link would be redundant.
The link starts hidden. The script shows it when window.self === window.top, which is only true when the page isn't loaded inside an iframe, such as the one the Presentation Tool renders.
Fetching data in pages
With all the infrastructure in place, fetching data in page components is straightforward. The pattern is the same on every page: call loadQuery with the query and spread getDraftModeProps(Astro.cookies).
---
import type { POSTS_QUERY_RESULT } from "../../sanity.types";
import { POSTS_QUERY } from "../sanity/lib/queries";
import { loadQuery } from "../sanity/lib/load-query";
import { getDraftModeProps } from "../sanity/lib/draft-mode";
import Layout from "../layouts/Layout.astro";
const { data: posts } = await loadQuery<POSTS_QUERY_RESULT>({
query: POSTS_QUERY,
...getDraftModeProps(Astro.cookies),
});
---
<Layout>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li>
<a href={`/post/${post.slug}`}>{post.title}</a>
</li>
))}
</ul>
</Layout>---
import type { POST_QUERY_RESULT } from "../../../sanity.types";
import { POST_QUERY } from "../../sanity/lib/queries";
import { loadQuery } from "../../sanity/lib/load-query";
import { getDraftModeProps } from "../../sanity/lib/draft-mode";
import Layout from "../../layouts/Layout.astro";
import PortableText from "../../components/PortableText.astro";
const { params } = Astro;
const { data: post } = await loadQuery<POST_QUERY_RESULT>({
query: POST_QUERY,
params,
...getDraftModeProps(Astro.cookies),
});
if (!post) {
return new Response(null, { status: 404 });
}
---
<Layout>
<h1>A post about {post.title}</h1>
<PortableText portableText={post.body} />
</Layout>The post page renders its body with a small PortableText.astro wrapper component built on @portabletext/astro, which you installed in the prerequisites:
---
import { PortableText as PortableTextRenderer } from "@portabletext/astro";
const { portableText } = Astro.props;
---
<PortableTextRenderer value={portableText} />Run both apps
With everything set up, run both apps to test. In separate terminal windows:
# Terminal 1: Start the Studio
cd studio
npm run dev
# Runs on http://localhost:3333# Terminal 1: Start the Studio
cd studio
pnpm run dev
# Runs on http://localhost:3333# Terminal 1: Start the Studio
cd studio
yarn run dev
# Runs on http://localhost:3333# Terminal 1: Start the Studio
cd studio
bun run dev
# Runs on http://localhost:3333# Terminal 2: Start the Astro frontend
cd frontend
npm run dev
# Runs on http://localhost:4321# Terminal 2: Start the Astro frontend
cd frontend
pnpm run dev
# Runs on http://localhost:4321# Terminal 2: Start the Astro frontend
cd frontend
yarn run dev
# Runs on http://localhost:4321# Terminal 2: Start the Astro frontend
cd frontend
bun run dev
# Runs on http://localhost:4321Open http://localhost:3333 in your browser and navigate to the Presentation Tool. You should see the Astro frontend loaded in the iframe with click-to-edit overlays on text elements.
The full flow
Now that you've seen every file, here's the complete sequence when an editor uses visual editing. This is the same flow described in "How the pieces fit together," but now you can trace each step back to the specific file that handles it:
- The editor opens the Presentation Tool in the studio (
studio/sanity.config.ts). - The studio loads
http://localhost:4321(theinitialURL) in an iframe and usesstudio/lib/resolve.tsto map the current document to a frontend URL. - The studio hits
http://localhost:4321/api/draft-mode/enablewith authentication parameters (frontend/src/pages/api/draft-mode/enable.ts). - The enable route validates the secret via
validatePreviewUrl, sets the cookie, and redirects to the requested page. - The page re-renders.
getDraftModeProps(frontend/src/sanity/lib/draft-mode.ts) reads the cookie and passes the value toloadQuery(frontend/src/sanity/lib/load-query.ts).loadQueryfetches draft content with stega-encoded strings: each string value has invisible characters that encode the document ID, field path, and studio URL (configured infrontend/astro.config.mjs). <VisualEditing />(rendered byfrontend/src/layouts/Layout.astroand enabled only during draft mode) reads the DOM, finds the stega-encoded strings, and renders transparent click-to-edit overlays on each text element.- The editor clicks an overlay. The overlay sends a
postMessageto the parent studio window with the document ID and field path. The studio navigates to that field. - The editor changes a field. The mutation propagates through the Content Lake, and
<VisualEditing />reloads the page (or updates it in place, withexperimental_refreshStrategy="in-place"). The page re-fetches from the server with the updated draft content.
Follow perspective changes from the studio
The draft mode enable route stores the perspective the editor had selected when the Presentation Tool enabled draft mode, such as drafts or a content release. <VisualEditing /> doesn't report later perspective changes to your page, so when the editor switches perspectives in the studio, the server keeps fetching with the stored one.
To follow perspective changes, render VisualEditingComponent from @sanity/astro/visual-editing/component instead. It's the React version of the component, and it accepts an onPerspectiveChange callback. The @sanity/astro README calls this React component deprecated, but it's the only way to receive onPerspectiveChange. It needs the React integration for Astro:
npm install @astrojs/react react react-dompnpm add @astrojs/react react react-domyarn add @astrojs/react react react-dombun add @astrojs/react react react-domAdd react() to the integrations in your Astro configuration:
import { defineConfig } from "astro/config";
import sanity from "@sanity/astro";
import react from "@astrojs/react";
import node from "@astrojs/node";
import { loadEnv } from "vite";
const { PUBLIC_SANITY_PROJECT_ID, PUBLIC_SANITY_DATASET } = loadEnv(
process.env.NODE_ENV,
process.cwd(),
"",
);
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
integrations: [
sanity({
projectId: PUBLIC_SANITY_PROJECT_ID,
dataset: PUBLIC_SANITY_DATASET,
useCdn: false,
apiVersion: "2026-03-01",
stega: {
studioUrl: "http://localhost:3333",
},
}),
react(),
],
vite: {
optimizeDeps: {
include: [
"react/compiler-runtime",
"react/jsx-runtime",
"lodash/isObject.js",
"lodash/groupBy.js",
"lodash/keyBy.js",
"lodash/partition.js",
"lodash/sortedIndex.js",
],
},
},
});Create a component that writes the new perspective to the perspective cookie and reloads the page, so the server fetches content with it:
import type { ClientPerspective } from "@sanity/client";
import { VisualEditingComponent } from "@sanity/astro/visual-editing/component";
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
function serializePerspective(perspective: ClientPerspective): string {
return typeof perspective === "string"
? perspective
: JSON.stringify(perspective);
}
function getCookie(name: string): string | undefined {
const match = document.cookie.match(
new RegExp(`(?:^|; )${name}=([^;]*)`),
);
return match ? decodeURIComponent(match[1]) : undefined;
}
function setPerspectiveCookie(perspective: ClientPerspective): boolean {
const next = serializePerspective(perspective);
if (getCookie(perspectiveCookieName) === next) return false;
// Match the attributes the enable route set. Inside the Presentation Tool this
// page runs in a cross-site iframe, so the cookie has to carry Partitioned or
// Safari drops the rewrite.
const partitioned = window.self !== window.top ? "; Partitioned" : "";
document.cookie = `${perspectiveCookieName}=${encodeURIComponent(next)}; path=/; SameSite=None; Secure${partitioned}`;
return true;
}
export default function SanityVisualEditing() {
return (
<VisualEditingComponent
onPerspectiveChange={(perspective) => {
if (setPerspectiveCookie(perspective)) {
window.location.reload();
}
}}
/>
);
}VisualEditingComponent has the same defaults as <VisualEditing />: it keeps the Presentation Tool's URL in sync and reloads the page on refresh. It also accepts experimental_refreshStrategy and every option of VisualEditing from @sanity/visual-editing/react, such as onSuspiciousStega, which reports stega-encoded strings in unsafe places like element attributes and <head>.
In the layout, render the component as a React island in place of <VisualEditing />:
---
import { perspectiveCookieName } from "@sanity/preview-url-secret/constants";
import DisableDraftMode from "../components/DisableDraftMode.astro";
import SanityVisualEditing from "../components/SanityVisualEditing";
const draftMode = Astro.cookies.has(perspectiveCookieName);
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>Astro Basics</title>
</head>
<body>
<slot />
{draftMode && <>
<SanityVisualEditing client:only="react" />
<DisableDraftMode />
</>}
</body>
</html>The client:only="react" directive renders the component only in the browser, with no server-side rendering attempt. This is necessary because it uses browser-only APIs (window and document.cookie).
Next steps
- Deploy to production: Update
stega.studioUrlinastro.config.mjs, the Presentation ToolinitialURL instudio/sanity.config.ts, and your CORS origins to point to your deployed URLs instead oflocalhost. It's common to use environment variables for these values with local fallbacks. Review the draft mode cookie settings too: the enable route setshttpOnly: falseso client-side code can read and rewrite the perspective cookie. If you don't follow perspective changes from the studio, you can set it totrue. For every integration option, see the @sanity/astro README. - Add more document types to
resolve.ts: Any document type that has a corresponding frontend route can get visual editing. Add entries to thelocationsobject for each type.
Troubleshooting
Overlays appear but clicking does nothing
Cause: stega.studioUrl is missing from the @sanity/astro integration config in frontend/astro.config.mjs.
Fix: Add stega: { studioUrl: 'http://localhost:3333' } to the sanity() integration options.
Presentation Tool shows a blank iframe
Cause: initial is missing from the Presentation Tool config in studio/sanity.config.ts. This only happens when the studio and frontend run as separate apps.
Fix: Add initial: 'http://localhost:4321' to previewUrl in the presentationTool() config.
Live preview doesn't update, 403 errors in browser console
Cause: The frontend's origin is missing from the Sanity project's CORS settings, so the browser can't reach the Content Lake.
Fix: Add http://localhost:4321 (with Allow credentials checked) in your project's CORS settings at sanity.io/manage under API → CORS Origins.
String comparisons fail in draft mode
Cause: Stega encoding adds invisible characters to string values. An equality check like align === 'center' returns false even when the visible value is "center" because the encoded string contains extra characters.
Fix: Use stegaClean() to strip the encoding before comparing:
import { stegaClean } from "@sanity/client/stega";
const cleanAlign = stegaClean(align);
if (cleanAlign === "center") {
// ...
}Module resolution errors in development
Cause: Vite's dev server serves some CommonJS dependencies of the Visual Editing overlays without converting them. The overlays don't appear, and the browser console shows an error such as [@sanity/astro] Failed to start Visual Editing SyntaxError: The requested module '/node_modules/lodash/isObject.js' does not provide an export named 'default'.
Fix: Add the problematic modules to vite.optimizeDeps.include in astro.config.mjs:
vite: {
optimizeDeps: {
include: [
"react/compiler-runtime",
"react/jsx-runtime",
"lodash/isObject.js",
"lodash/groupBy.js",
"lodash/keyBy.js",
"lodash/partition.js",
"lodash/sortedIndex.js",
],
},
},Production builds aren't affected, so these entries only matter for astro dev.
Draft mode not activating
Cause: The browser blocks the cookie because it requires SameSite=None; Secure, which in turn requires HTTPS (or localhost).
Fix: Ensure you're accessing the frontend via localhost (not an IP address or custom domain) during development. For deployed environments, ensure HTTPS is enabled.
Draft mode works in Chrome but not Safari
Cause: Safari blocks third-party cookies that aren't partitioned. The studio loads your frontend in a cross-site iframe, so the cookie set by /api/draft-mode/enable counts as third-party and never gets stored. The Presentation Tool reports "Unable to connect to visual editing" and draft mode never activates. Chrome is more permissive, which is why the same setup works there.
Fix: Set the CHIPS Partitioned attribute on the cookie when the enable route is hit from a cross-site iframe, and expire both the partitioned and unpartitioned variants in the disable route. The route examples in this guide do this. If you follow perspective changes from the studio, the cookie that SanityVisualEditing.tsx writes needs the same attribute.
Page titles contain garbled text in draft mode
Cause: If you render queried content in <title> or <meta> tags, stega characters will be embedded in them.
Fix: Use stegaClean() from @sanity/client/stega to strip encoding before inserting into metadata:
import { stegaClean } from "@sanity/client/stega";
// In your .astro frontmatter:
const cleanTitle = stegaClean(post.title);Then use cleanTitle in the <title> tag.
Reference
Key packages
sanity(6.x): Sanity Studioastro(7.x): Astro framework@sanity/astro(4.x): Sanity integration for Astro (client, stega config, Visual Editing component)@astrojs/react(7.x): React integration, only needed to follow perspective changes from the studio@astrojs/node(11.x): Node.js server adapter@sanity/client(7.28+ or 8.11+): Sanity client used by thesanity:clientmodule and for query types@sanity/preview-url-secret(latest): Preview URL validation for draft modegroq:defineQueryfor typed GROQ queries@sanity/image-url(2.1.x): Image URL generation@portabletext/astro(0.x): Portable Text rendering for Astro
File map
Every file involved in the visual editing integration, what it does, and what it depends on:
studio/sanity.config.ts(Configures the Presentation Tool with the frontend's initial URL andpreviewMode.enablepath):studio/lib/resolve.tsstudio/lib/resolve.ts(Maps document types to frontend URLs for iframe navigation and location badges): Schema type names, frontend route structure insrc/pages/frontend/astro.config.mjs(Astro config: SSR,@sanity/astrointegration withstega.studioUrl, Vite optimizeDeps):PUBLIC_SANITY_PROJECT_ID,PUBLIC_SANITY_DATASETfrontend/src/env.d.ts(Triple-slash references forastro/clientand@sanity/astro/moduletype definitions): Nothingfrontend/src/sanity/lib/draft-mode.ts(Reads draft mode and perspective cookies fromAstro.cookies): Nothingfrontend/src/sanity/lib/load-query.ts(Fetches content with perspective/stega switching based on draft mode):sanity:client,SANITY_API_READ_TOKENfrontend/src/sanity/lib/queries.ts(Centralized GROQ queries wrapped indefineQuery):groqfrontend/src/components/SanityVisualEditing.tsx(Optional. Follows perspective changes from the studio by writing the perspective cookie):@sanity/astro/visual-editing/component,@astrojs/reactfrontend/src/components/DisableDraftMode.astro(Floating link to exit draft mode, hidden when inside the Presentation Tool): Nothingfrontend/src/components/PortableText.astro(Renders Portable Text content using@portabletext/astro):@portabletext/astrofrontend/src/layouts/Layout.astro(Shared layout: Visual Editing and the Disable Draft Mode link during draft mode):@sanity/astro/visual-editing,DisableDraftMode.astrofrontend/src/pages/api/draft-mode/enable.ts(Validates Presentation Tool secret, sets the perspective cookie):sanity:client,@sanity/preview-url-secret,SANITY_API_READ_TOKENfrontend/src/pages/api/draft-mode/disable.ts(Clears cookies, redirects to homepage): Nothing
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?