@sanity/astro
v4.0.0
Published
Official Sanity Astro integration
Readme
The Official Sanity integration for Astro
This integration enables the Sanity Client in your Astro project and lets you embed Sanity Studio on a route. Astro is an all-in-one web framework that supports a range of UI languages and can be deployed in most places.
- Installation
- Usage
- Live collections
- Rendering rich text and block content with Portable Text
- Presenting images
- Enabling Visual Editing
- Examples
Installation
In your Astro project, run the following command to install the Sanity integration:
npx astro add @sanity/astro @astrojs/reactNote: @astrojs/react is only needed if you plan to embed a Sanity Studio in your project.
Manual installation of dependencies
npm install @astrojs/react @sanity/astro @sanity/client sanity @types/react-dom @types/react-is @types/react react-dom react-is react styled-componentsTypes for sanity:client and sanity:studio
This integration leverages Vite.js' virtual modules with Astro's naming convention (e.g. astro:assets). Add this line to the env.d.ts file in the src folder of your project:
/// <reference types="astro/client" />
/// <reference types="@sanity/astro/module" />On Astro 4.14 and later you can let the integration register the declarations instead, by setting injectTypes: true in the integration options. They then land in .astro/integrations/_sanity_astro/types.d.ts after astro dev, astro build or astro sync through Astro's injectTypes, and the env.d.ts line can go. The option is off by default; keeping the manual reference alongside it is harmless. Setting the clients option also adds the reference on Astro 4.14 and later (see Typed queries per client).
sanity({
projectId: '<YOUR-PROJECT-ID>',
dataset: '<YOUR-DATASET-NAME>',
injectTypes: true,
})You might have to restart the TS Server running in your code editor to get it to resolve types after updating this file. The easiest way to do this is to restart the application.
Usage
Setting up the Sanity client
Configure the integration in your astro.config.mjs file. The configuration options and methods are the same as for @sanity/client:
import sanity from '@sanity/astro'
import {defineConfig} from 'astro/config'
// https://astro.build/config
export default defineConfig({
integrations: [
sanity({
projectId: '<YOUR-PROJECT-ID>',
dataset: '<YOUR-DATASET-NAME>',
// Set useCdn to false if you're building statically.
useCdn: false,
// Optional: log server-side Sanity client requests.
// Modes: 'dev' | 'build' | 'always'
logClientRequests: 'dev',
}),
],
})This enables the use of sanityClient in your template files. For example:
---
// /blog/index.astro
import { sanityClient } from "sanity:client";
const posts = await sanityClient.fetch(`*[_type == "post" && defined(slug)] | order(publishedAt desc)`);
---
<h1>Blog</h1>
<ul>
{posts.map((post) => (
<li>
<a href={'/posts/' + post.slug.current} class="post-link">
{post.title}
</a>
</li>
))}
</ul>Check out this guide for a more elaborate introduction to how to integrate content from Sanity into Astro. You can also look in the apps folder in this repository for complete implementation examples.
To log server-side requests made with sanity:client, set logClientRequests in your integration config:
logClientRequests: 'dev'logs during developmentlogClientRequests: 'build'logs during static buildslogClientRequests: 'always'logs during both development and builds
If omitted, request logging is disabled.
Reading projectId and dataset at runtime
projectId and dataset are written into the build. To build once and choose them when the server starts, for example when the same Docker image runs in several environments, name the environment variables in env:
sanity({
// Build-time values
projectId: '<YOUR-PROJECT-ID>',
dataset: 'production',
// Read on the server when it runs
env: {projectId: 'SANITY_PROJECT_ID', dataset: 'SANITY_DATASET'},
studioBasePath: '/admin',
})The integration reads the variables at runtime with getSecret from astro:env/server, so they don't need to be declared in env.schema. Requires Astro 5 or later.
The values apply to sanityClient in server code rendered on demand, and to the embedded Studio with browser history, which receives them in the rendered page, falls back to sanity.config.ts and supports a single workspace only; an array of workspaces throws. Everything else keeps the build-time values: browser code, other named clients, the Studio with hash history, and prerendered pages and sanityLoader, which run during the build and read the variables only if they are set then.
Loading Sanity documents into content collections
On Astro 5 and later, sanityLoader feeds a GROQ query into the Content Layer, so getCollection() and getEntry() work the same way for Sanity documents as for local Markdown. The loader is experimental: it is opt-in through its own @sanity/astro/loader entrypoint and its options may change in a minor release. Pass the client from sanity:client so the loader reuses your integration config:
// src/content.config.ts
import {sanityLoader} from '@sanity/astro/loader'
import {defineCollection} from 'astro:content'
import {z} from 'astro/zod'
import {sanityClient} from 'sanity:client'
const movies = defineCollection({
loader: sanityLoader<{_id: string; slug: string}>({
client: sanityClient,
query: `*[_type == "movie" && defined(slug.current)]{_id, title, "slug": slug.current, releaseDate}`,
// Entry ids default to `_id`. Use the slug when pages are addressed by it.
id: (movie) => movie.slug,
}),
schema: z.object({
_id: z.string(),
title: z.string(),
slug: z.string(),
releaseDate: z.string().optional(),
}),
})
export const collections = {movies}---
// src/pages/movies/[slug].astro
import {getCollection} from 'astro:content'
export async function getStaticPaths() {
const movies = await getCollection('movies')
return movies.map((movie) => ({params: {slug: movie.id}, props: {movie}}))
}
const {movie} = Astro.props
---
<h1>{movie.data.title}</h1>Every load fetches the whole query result, writes each document with a content digest so unchanged entries are skipped, and removes entries that left the result, so edits and deletions in Sanity show up on the next build or dev-server restart. Two documents mapping to the same entry id (for example a draft and its published document when the query uses the raw or drafts perspective) make the loader throw, naming both _ids, rather than silently dropping one.
Multiple clients
To read from more than one project or dataset, configure named clients with the clients option. Each entry takes the same options as @sanity/client. clients.default is the client exported as sanityClient, so existing code keeps working:
import sanity from '@sanity/astro'
import {defineConfig} from 'astro/config'
export default defineConfig({
integrations: [
sanity({
clients: {
default: {
projectId: '<YOUR-PROJECT-ID>',
dataset: 'marketing',
useCdn: false,
},
community: {
projectId: '<COMMUNITY-PROJECT-ID>',
dataset: 'community',
useCdn: true,
},
},
}),
],
})Top-level client options (projectId, dataset, …) still work and configure the default client. They can be combined with clients as long as clients has no default entry of its own.
Every client is available through getClient(name), and sanityClient stays the default one:
---
import {getClient, sanityClient} from 'sanity:client'
const posts = await sanityClient.fetch(`*[_type == "post"]`)
const members = await getClient('community').fetch(`*[_type == "member"]`)
---Calling getClient with a name that is not configured throws, and the generated types reject it at compile time as well. To pass names around, type them with the ClientName type exported from sanity:client.
Named clients that are configured with a token or headers are only available in server code (frontmatter, endpoints, middleware). In the browser, getClient(name) returns a stand-in for them that throws on first use, so the credentials never end up in a client bundle. presentationClient is that same stand-in when it points at such a client. The default client is shipped to the browser as before, so keep its token out of the integration config and pass it per request instead, like the loadQuery helper below does.
The presentation client
Mark the client your Presentation and Visual Editing code reads from with presentation: true; without the flag the default client is used. The flag only decides which client the presentationClient export returns, the client itself is configured like any other, so give it the stega.studioUrl from Enable Stega:
sanity({
studioBasePath: '/admin',
clients: {
default: {projectId: '<YOUR-PROJECT-ID>', dataset: 'marketing'},
community: {
projectId: '<COMMUNITY-PROJECT-ID>',
dataset: 'community',
presentation: true,
stega: {studioUrl: '/admin'},
},
},
})Read from presentationClient in the helpers that feed Presentation, so they follow the flag instead of hardcoding a name. In the loadQuery helper from Enable Stega that is a one-line change:
// load-query.ts
import {presentationClient} from 'sanity:client'
// ...
const {result, resultSourceMap} = await presentationClient.fetch<QueryResponse>(
query,
params ?? {},
{
filterResponse: false,
perspective,
resultSourceMap: visualEditingEnabled ? 'withKeyArraySelector' : false,
stega: visualEditingEnabled,
...(visualEditingEnabled ? {token} : {}),
useCdn: !visualEditingEnabled,
},
)Only one client can set presentation: true.
Typed queries per client
When the clients option is set (Astro 4.14 or later), the integration writes the configured client names to .astro/integrations/_sanity_astro/clients.d.ts whenever Astro syncs types (astro dev, astro build, astro check, astro sync). That types getClient(name) and rejects unknown names. Combine it with Sanity TypeGen and the typegen.resources option (beta, @sanity/cli 8.16.0 or later, which bundles @sanity/codegen 8.2.0 or later) in sanity.cli.ts to get query result types per project and dataset:
// sanity.cli.ts
import {defineCliConfig} from 'sanity/cli'
export default defineCliConfig({
typegen: {
resources: [
{
projectId: '<YOUR-PROJECT-ID>',
dataset: 'marketing',
schema: './schema.json',
path: './src/marketing/**/*.{ts,tsx,astro}',
generates: './src/sanity/marketing.types.ts',
},
{
projectId: '<COMMUNITY-PROJECT-ID>',
dataset: 'community',
path: './src/community/**/*.{ts,tsx,astro}',
generates: './src/sanity/community.types.ts',
},
],
},
})Each generated file augments the global SanityQueriesByResource registry under its "projectId.dataset" key. The integration maps every client to its key, so getClient('community').fetch(MEMBERS_QUERY) returns the community result type while sanityClient.fetch(POSTS_QUERY) returns the marketing one:
import {defineQuery} from 'groq'
const POSTS_QUERY = defineQuery(`*[_type == "post"]`)
const MEMBERS_QUERY = defineQuery(`*[_type == "member"]`)TypeGen only picks up queries tagged with groq or wrapped in defineQuery, and fetch matches results by the query's literal type, which defineQuery keeps and the groq tag widens to string. Use defineQuery for queries fetched through a typed client: a groq-tagged query, or an inline string TypeGen never saw, resolves to any. Things to know:
- Run
npx sanity typegen generateafter changing queries, or keepnpx sanity typegen generate --watchrunning (@sanity/cli8.22.0 or later; older versions reject--watchtogether withtypegen.resources).sanity dev's built-in typegen does not supporttypegen.resourcesyet. - Give each resource its own
pathglob. Every query in the matched files is typed against that resource's schema, so overlapping globs type the same query against both schemas. - A resource without
schemauses the schema deployed for that project and dataset, sonpx sanity schema deployhas to have run for it. projectIdanddatasethave to match the client config exactly. A mismatch is not an error, the client just stays an untypedSanityClient.- With
typegen.resources,overloadClientMethodsdefaults tofalse, so the flatSanityQueriesregistry from single-resource typegen is not written. Typed clients resolve results throughSanityQueriesByResourceonly, a leftover flat registry has no effect on them. A query imported from a.groqfile (see Typing query results) brings its own types, which win over the registry.
Without typegen.resources, every client is a regular SanityClient.
Typing query results
sanityClient is a regular SanityClient, so sanityClient.fetch resolves the types Sanity TypeGen generates for defineQuery queries, and takes an explicit generic, sanityClient.fetch<Post[]>(query), for everything else.
With @sanity/client 7.28.0 or later on v7, or 8.11.0 or later on v8, it also infers the result and checks the params of a query you import from a .groq file through @sanity-labs/groq-content-mapper. No generic, no generated registry. Both the mapper and the client's support for it are experimental, and the mapper needs TypeScript 7.1 (currently typescript@beta). Its README covers the requirements.
npm install -D @sanity-labs/groq-content-mapper typescript@beta
npx sanity schema extract --path ./schema.json # the default pathAstro builds with Vite, so the mapper's Vite plugin loads .groq files as strings:
// astro.config.mjs
import sanity from '@sanity/astro'
import groqFiles from '@sanity-labs/groq-content-mapper/vite'
import {defineConfig} from 'astro/config'
export default defineConfig({
integrations: [sanity({projectId: '<YOUR-PROJECT-ID>', dataset: '<YOUR-DATASET-NAME>'})],
vite: {plugins: [groqFiles()]},
})The tsconfig points the mapper at the schema sanity schema extract writes:
// tsconfig.json
{
"extends": "astro/tsconfigs/strict",
"contentMappers": [
{
"package": "@sanity-labs/groq-content-mapper",
"extensions": [".groq"],
"options": {
"schema": "./schema.json",
// Only when you query more than one project or dataset, one schema per folder:
// "schemas": [{"include": "src/queries/blog", "schema": "./schemas/blog.json"}],
},
},
],
}Then write the query in its own file and import it:
// src/queries/postBySlug.groq
*[_type == "post" && slug.current == $slug][0]{title, publishedAt}// src/lib/posts.ts
import {sanityClient} from 'sanity:client'
import postBySlug from '../queries/postBySlug.groq' with {type: 'text'}
export async function getPost(slug: string) {
return sanityClient.fetch(postBySlug, {slug})
// ^? Promise<{title: string | null; publishedAt: string | null} | null>, and `slug` is checked
}The types only exist when TypeScript runs the mapper, so type-check with tsc --noEmit --runExternalCode. astro check runs on TypeScript 5 or 6, which have no content mappers, so keep .groq imports in .ts modules like the one above rather than in a component's frontmatter.
sanityLoader reads the same types. Pass a .groq import as its query and it checks params and types the id callback, no generic needed:
// src/content.config.ts
import {sanityLoader} from '@sanity/astro/loader'
import {defineCollection} from 'astro:content'
import {sanityClient} from 'sanity:client'
import moviesByGenre from './queries/moviesByGenre.groq' with {type: 'text'}
const movies = defineCollection({
loader: sanityLoader({
client: sanityClient,
query: moviesByGenre,
params: {genre: 'drama'},
id: (movie) => movie.slug, // `movie` is typed from the query's projection
}),
})If you wrap sanityClient.fetch in a helper of your own, such as the loadQuery in Enabling Visual Editing, type it with the client's ClientReturn and ClientParams so the inferred types pass through. Plain strings, explicit generics and TypeGen queries keep resolving as before:
import type {ClientParams, ClientReturn} from '@sanity/client'
import {sanityClient} from 'sanity:client'
export async function sanityFetch<const Q extends string>(
query: Q,
params?: ClientParams<Q>,
): Promise<ClientReturn<Q, unknown>> {
return sanityClient.fetch(query, params ?? {})
}Embedding Sanity Studio on a route
Sanity Studio is a customizable content workspace where you can edit your content. It‘s a Single Page Application that you can keep in its own repository, together with your Astro project as a monorepo, or embedded in your website.
To initialize a Studio in a dedicated folder, you can run npm create sanity@latest and follow the instructions.
This integration lets you embed a Sanity Studio on a route in your Astro project. To enable it:
- Create a new file in your project root called
sanity.config.ts(or.js) - Add the following code, and add your
projectIdanddatasetto it:
// sanity.config.ts
import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
export default defineConfig({
name: 'project-name',
title: 'Project Name',
projectId: '<YOUR-PROJECT-ID>',
dataset: '<YOUR-DATASET-NAME>',
plugins: [structureTool()],
schema: {
types: [/* your content types here*/],
},
})You can use this configuration file to install plugins, add a schema with document types, add customizations etc. Note that the Studio will be using Astro‘s development server which is built on top of Vite.
- Add the following to your
astro.config.mjs:studioBasePath: '/admin': The route/path for where you want to access your studio- Import the React integration for Astro, and add it to the
integrationsarray.
// astro.config.mjs
import sanity from '@sanity/astro'
import {defineConfig} from 'astro/config'
import react from '@astrojs/react'
export default defineConfig({
integrations: [
sanity({
projectId: '3do82whm',
dataset: 'next',
// Set useCdn to false if you're building statically.
useCdn: false,
// Access the Studio on your.url/admin
studioBasePath: '/admin',
}),
react(),
],
})- You have to enable CORS origins for authenticated requests for the domains you're running your website project on. The Studio should automatically detect and let you add this when you access the Studio on a new URL. Typically you need to add your local development server URL and your production URL to the CORS origin settings. It's important that you only enable CORS for authenticated requests on domains that you control.
Workspaces in embedded Studio
Sanity workspaces are supported by exporting an array from defineConfig (see Studio Workspaces).
When Studio is embedded through @sanity/astro, the integration owns workspace basePath values so all workspaces stay mounted under your configured studioBasePath route:
- In browser-history mode (
studioRouterHistoryomitted or'browser'), workspaces are mounted as:- single workspace:
/<studioBasePath>(for example/admin) - multiple workspaces:
/<studioBasePath>/<workspace-name>for every workspace
- single workspace:
- In hash-history mode (
studioRouterHistory: 'hash'), workspaces are mounted inside the hash router:- single workspace:
#/ - multiple workspaces:
#/<workspace-name>for every workspace
- single workspace:
- If
studioRouterHistoryis omitted, the integration defaults to hash history for Astrooutput: 'static', and browser history for server output.
If you are also using Visual Editing stega, set stega.studioUrl to your Studio route path (for example '/admin') and avoid appending a manual hash suffix.
Live collections
Experimental. Everything in this section is opt-in behind the
experimental_liveoption and may change in minor releases. With the option unset, the integration behaves exactly as before: no schema extraction, nosanity:loadermodule, no extra hooks. The@sanity/astro/loaderentry point it relies on is experimental too.
Astro 6 and later can serve content through live collections, which fetch on every request instead of at build time. Where sanityLoader loads a query into the Content Layer at build time, the experimental_live option generates a typed live loader and a Zod schema for each document type you list, derived from your Sanity schema:
// astro.config.mjs
sanity({
projectId: '<YOUR-PROJECT-ID>',
dataset: '<YOUR-DATASET-NAME>',
experimental_live: {
schema: './sanity.config.ts',
loaders: {
movie: {
type: 'movie',
projection: 'title, releaseDate, poster, "slug": slug.current',
orderBy: ['title', 'asc'],
},
},
},
})experimental_live.schema accepts either kind of input:
- A
sanity.config.ts(or.js,.mjs,.tsx,.jsx). The integration extracts the schema itself with the same node API assanity schema extract, using thesanitypackage installed next to that config. This needssanity5.29 or later (@sanity/cli6.7 or later); on older versions extract the schema yourself and use the.jsonform. - A
schema.jsonproduced bynpx sanity schema extract, which can live in another directory or repository.
The object form adds extraction options:
experimental_live: {
schema: {
path: '../studio/sanity.config.ts',
workspace: 'default', // only needed when the config defines several workspaces
enforceRequiredFields: false,
// extra globs, relative to the studio directory, that re-extract the schema in dev
// (same shape as `schemaExtraction.watchPatterns` in sanity.cli.ts)
watchPatterns: ['src/lib/**/*.ts'],
},
loaders: {...},
}Each key in experimental_live.loaders becomes a set of exports on the sanity:loader virtual module: <key>Loader, <key>Schema and the type <Key> (blog-posts gives blogPostsLoader, blogPostsSchema and BlogPosts). A loader takes:
type(required): the document_typethe loader serves.filter: an extra GROQ condition, combined with the type check using&&.projection: the GROQ projection body, defaulting to...._idand_updatedAtare always added;_idis the entry id and_updatedAtitslastModifiedcache hint.orderBy: a[field, 'asc' | 'desc']tuple or a list of them, applied to the collection query only.entryBy: which field the id passed togetLiveEntryis compared with.'id'(default) matches_id == $id;'slug'matchesslug.current == $id, sogetLiveEntry('people', 'ridley-scott')looks the person up by slug.
Wire the loaders up in src/live.config.ts:
import {defineLiveCollection} from 'astro:content'
import {movieLoader, movieSchema} from 'sanity:loader'
export const collections = {
movies: defineLiveCollection({loader: movieLoader(), schema: movieSchema}),
}movieLoader() uses the sanity:client instance and is built on createSanityLiveLoader from @sanity/astro/loader, the same experimental entry point as sanityLoader. Pass your own client for Draft Mode or Visual Editing:
import {sanityClient} from 'sanity:client'
const client = sanityClient.withConfig({
token: import.meta.env.SANITY_API_READ_TOKEN,
perspective: 'drafts',
useCdn: false,
stega: true,
})
movieLoader({client})The generated Zod schema strips stega characters from string literals (_type, portable text style and listItem, and other enums) before checking them, so those comparisons keep working. Prose fields are left encoded for Visual Editing.
Then query the collection in your pages. getLiveCollection accepts flat GROQ parameters as its filter, and getLiveEntry takes the id (or {id, ...params} to bind extra GROQ parameters):
---
import {getLiveCollection, getLiveEntry} from 'astro:content'
const {entries, error} = await getLiveCollection('movies')
const {entry} = await getLiveEntry('movies', 'movie-alien')
// entry.data is typed as Movie: {_id: string; _updatedAt: string; title: string | null; ...}
---In a dynamic route, check the parameter first (Astro.params.id is typed string | undefined) and return a 404 when the entry is missing; apps/movies/src/pages/movies/[id].astro shows the full pattern.
The generated files live in .astro/integrations/_sanity_astro/: schema.json (when extracting from a studio config) and sanity-loader.d.ts, which Astro references from .astro/types.d.ts so the exports of sanity:loader are typed without any manual setup. astro build and astro sync always extract a fresh schema. astro dev starts from the previous schema.json so the server is ready immediately, re-extracts in the background, and re-extracts again whenever a schema file changes, regenerating sanity:loader and its types in place. Which files count is decided by the patterns of sanity schema extract --watch from the installed CLI (sanity.config.* and schema*/**/*.{js,jsx,ts,tsx,mjs} next to it) plus your watchPatterns.
Rendering rich text and block content with Portable Text
Sanity uses an open specification for rich text and block content called Portable Text. Portable Text stores content from the editor as JSON (and not HTML or Markdown). This makes it platform/framework agnostic, and also queryable (for example, you can query for blog posts that have more than 4 TypeScript code blocks).
While it's possible to loop over the JSON structure manually, we recommend using a Portable Text library to do the heavy lifting. It will automatically render the default editor configuration to HTML. If you do customizations like adding custom block types, then you need to map those to a component in your front end.
We recommend using astro-portabletext to render your PortableText fields in Astro. See an example of this in apps/example/src/components/PortableText.astro, including using custom components to render custom blocks and annotations.
---
import {PortableText as PortableTextInternal} from "astro-portabletext"
import CallToActionBox from "./CallToActionBox.astro";
import Code from "./Code.astro";
import SanityImage from "./SanityImage.astro";
import YouTube from "./YouTube.astro";
import InternalLink from "./InternalLink.astro";
const components = {
type: {
callToActionBox: CallToActionBox,
code: Code,
image: SanityImage,
youtube: YouTube,
},
mark: {
internalLink: InternalLink
}
};
---
<PortableTextInternal value={Astro.props.value} components={components} />Presenting images
Sanity comes with a native asset pipeline for your images and files. It has on-demand transforms, automatic optimization for browsers that supports webp, and serves images from a global CDN network. When you upload images to Sanity, it will also automatically analyze the image and add a metadata document with information like dimensions, color palette, generate blurhash, and LQIP strings.
We recommend using @sanity/image-url to help you generate URLs for presenting Sanity images in your Astro app. See an example of this in apps/example/src/components/SanityImage.astro
You can also use community-contributed integrations like astro-sanity-picture to integrate images from Sanity into your website.
Enabling Visual Editing
To enable Visual Editing, you need to:
- Enable Overlays using the
VisualEditingcomponent - Add the Presentation tool to the Studio
- Enable Stega
Please note that Visual Editing only works for server-side rendered pages. This means you probably want to configure your Astro project something like this:
import vercel from '@astrojs/vercel'
// astro.config.mjs
export default defineConfig({
integrations: [
sanity({
useCdn: true,
// ...
}),
// ...
],
output: 'server',
adapter: vercel(),
})1. Enable Overlays using the VisualEditing component
Add VisualEditing from @sanity/astro/visual-editing in your "page shell" layout:
---
import {VisualEditing} from '@sanity/astro/visual-editing'
export type props = {
title: string
}
const {title} = Astro.props
const visualEditingEnabled = import.meta.env.PUBLIC_SANITY_VISUAL_EDITING_ENABLED == 'true'
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
</head>
<body>
<slot />
<VisualEditing enabled={visualEditingEnabled} zIndex={1000} />
<!-- ^optional -->
</body>
</html>VisualEditing renders the Overlays from a plain <script>. It does not need the React integration for Astro or any React component in your project, so a site built only from .astro files gets Visual Editing by adding this one component. See apps/minimal for a React-free setup. The overlay chunk is emitted into your build output whether or not enabled is true, exactly as the React island before it was; a page with Visual Editing off never fetches it.
VisualEditing takes these props:
enabled: so you can control whether or not visual editing is enabled depending on your environment.zIndex(optional): allows you to change thez-indexof overlay elements.keepStegaOnCopy(optional): by default, Visual Editing strips stega from the clipboard on copy. PasskeepStegaOnCopyto opt out and leave stega in copied text.experimental_refreshStrategy(optional, experimental, opt-in): how the preview catches up with an edit. Unset (the default) reloads the page, as it always has.{type: 'reload', followUpDelayMs}adds one follow-up reload after a change, and'in-place'refreshes the page without reloading it. See How the preview refreshes.
In the example above, enabled is controlled using an environment variable:
// .env.local
PUBLIC_SANITY_VISUAL_EDITING_ENABLED="true"How the preview refreshes
By default VisualEditing reloads the whole page with window.location.reload() whenever Presentation asks for a refresh: when the editor clicks the refresh button, and when the document open in the Studio changes. That is what this integration has always done, and nothing below changes it unless you opt in with experimental_refreshStrategy. It's accepted by both the .astro VisualEditing component and VisualEditingComponent, and it's ignored when you pass your own refresh:
| Strategy | What the editor sees | Trade-off |
| ----------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 'reload' (default) | The page reloads on every refresh. | Every edit costs a full page load and resets scroll, focus and form state, but the page is always exactly what the server renders and every script runs again. |
| {type: 'reload', followUpDelayMs: 1200} | The page reloads, then reloads once more followUpDelayMs after it is back. | Catches text typed in the Studio while the first reload was in flight, which a plain reload can miss until the next edit, at the cost of a second reload per change. A snapshot that lands during the reload, or a dropped refresh, arms it. Needs sessionStorage. |
| 'in-place' | Stega text updates as the editor types, then the page morphs to the fresh server HTML. | Scroll, focus and the Presentation connection survive, but DOM injected by third-party scripts is removed and those scripts do not run again. See below. |
<VisualEditing
enabled={visualEditingEnabled}
experimental_refreshStrategy={{type: 'reload', followUpDelayMs: 1200}}
/>An object prop needs Astro's double brackets, {{ }}, so the template passes the object rather than its text.
Experimental: refreshing in place
Pass experimental_refreshStrategy="in-place" to update the page without reloading it:
<VisualEditing enabled={visualEditingEnabled} experimental_refreshStrategy="in-place" />Edits then reach the page in two steps.
- Instant text. Presentation streams document changes to the overlays.
VisualEditinglistens to that stream and rewrites the stega-encoded text nodes rendered from the changed document as soon as the change arrives, before any request to your server. A node is rewritten only once the page has been seen rendering that field verbatim and the node still shows a value the field held before. Text your page transformed (truncated, formatted, upper-cased) and text built from several fields are left to the server render. - In-place morph. Half a second after the last change,
VisualEditingfetches the current URL and patches the live DOM with idiomorph so it matches the fresh server HTML. Everything the text patch cannot express (ordering, images, dates, references, conditionally rendered markup) updates here. Scroll position, focus, form state and the Presentation connection survive because the document never navigates. If the server has not caught up with the change yet, the fetch retries briefly, and a settle pass runs one second later.
The morph makes the DOM match the server HTML, with a short list of exceptions. It leaves the overlay host, Astro's dev toolbar and Vite's error overlay alone. In <head> it keeps only nodes a client injected at runtime, recognised by the data-vite-dev-id, data-styled, data-styled-version or data-astro-transition-persist attribute; every other head node, including <title>, <meta>, <link> and <script> tags, is reconciled against the fresh HTML. Hydrated <astro-island> elements keep their client-rendered subtree and receive the new props attribute, which Astro re-hydrates from. Form controls the visitor has typed in or toggled keep their value, and class and style on <html> and <body> stay as client scripts left them.
DOM that a third-party script injected is removed by the morph. Cookie banners, chat widgets, analytics beacons, A/B testing snippets and similar scripts add elements the server HTML does not contain, so the morph deletes them, and they are not re-created until the next real page load. Mark such an element with Astro's transition:persist attribute (data-astro-transition-persist when a script creates it) if you control it. If you cannot, or if a script relies on running again after each change, keep the default 'reload' strategy on that site. This is one of the reasons the in-place refresh is opt-in.
When the fetch fails, the response is not HTML, the request was redirected elsewhere, or the fresh HTML introduces a <script> the page does not have yet, VisualEditing falls back to a full reload. The script case exists because a script parsed from a fetched document can be inserted but never executed, so only a reload gives it the behaviour the server intended. Should the in-place refresh itself throw, the error is logged once and the page reloads on every refresh from then on, instead of the failure hiding behind a reload.
Visual Editing needs fresh HTML per request, so run the site with astro dev or an SSR adapter while previewing.
Two limits are worth knowing. Values rendered from a release perspective are not patched instantly, because the overlays stream the draft and published forms of a document but not its version form; those update through the morph. And the option is experimental: while it carries the experimental_ prefix, its name and behaviour can change in a minor release.
Running the overlays on @sanity/visual-editing-standalone (optional)
By default the overlays come from @sanity/visual-editing, which Vite bundles together with your project's copy of React, React DOM and styled-components. Set visualEditingStandalone: true to load them from @sanity/visual-editing-standalone instead. It is a self-contained build with its own copy of those libraries, so the overlays don't depend on the versions installed in your project. Install it next to @sanity/astro:
npm install @sanity/visual-editing-standalone// astro.config.mjs
export default defineConfig({
integrations: [
sanity({
// ...
visualEditingStandalone: true,
}),
],
})Only the VisualEditing component switches; the deprecated React component keeps using @sanity/visual-editing. The standalone build isn't smaller: in apps/minimal the script that boots the overlays shrinks, and the lazily loaded overlay chunk grows by the overlay stylesheet. The client inserts that CSS into <head> with data-astro-transition-persist, so an in-place refresh keeps it. If your project uses the React integration for Astro, the overlays then ship a second copy of React, and the integration logs a warning.
With experimental_refreshStrategy="in-place", the instant text step doesn't work in this mode. It reads the overlays' document state from @sanity/visual-editing/optimistic, and the standalone build keeps its own copy of that state without exporting it. With both options on, edits don't patch the page's text in place. The in-place morph and the default page reload still run.
Customizing how the preview refreshes
If you'd rather refresh another way, for example re-fetching data and swapping the DOM in place yourself, pass your own refresh function.
refresh is a function, and Astro can't serialize functions through to a client component, so it isn't accepted on the .astro VisualEditing component. Instead, import the React component from @sanity/astro/visual-editing/component and render it as a client:only island. It needs the React integration for Astro:
// src/components/VisualEditing.tsx
import {VisualEditingComponent} from '@sanity/astro/visual-editing/component'
export default function VisualEditing() {
return (
<VisualEditingComponent
refresh={(payload) => {
// Return a promise so the overlay shows a loading state until it resolves.
return new Promise((resolve) => {
// ...your custom refresh here, then:
resolve()
})
}}
onSuspiciousStega={(reports) => {
for (const report of reports) {
console.warn(`Stega found in ${report.kind}`, report)
}
}}
/>
)
}---
// src/layouts/Layout.astro
import VisualEditing from '../components/VisualEditing'
const visualEditingEnabled = import.meta.env.PUBLIC_SANITY_VISUAL_EDITING_ENABLED === 'true'
---
<body>
<slot />
{visualEditingEnabled && <VisualEditing client:only="react" />}
</body>The payload tells you why the refresh fired: payload.source is 'manual' when the editor clicks refresh in Presentation, or 'mutation' when a document changes.
VisualEditingComponent accepts the full VisualEditingOptions type from @sanity/visual-editing/react and forwards it unchanged, plus this integration's own experimental_refreshStrategy (see above), which is not forwarded. The one prop of <VisualEditing /> it does not take is portal, which is always on. Beyond refresh, the ones worth knowing about are:
history: take over URL syncing. When omitted, the built-in adapter keeps Presentation's URL bar in sync with the preview.onSuspiciousStega: opt-in reporting when stega appears in unsafe placements (class,href,<head>, scripts, and similar).onPerspectiveChange/onVariantChange: keep server-side fetching on the same perspective and variant as the Studio driving the preview.components(alpha): a resolver for custom overlay UI, such as an insert menu on an array field.plugins(alpha): an array of overlay plugin definitions.experimental_refreshStrategy: the same option as on the.astrocomponent. It is ignored when you pass your ownrefresh.
refresh falls back to window.location.reload() and history to the built-in adapter when you don't pass them; everything else is passed straight through. The alpha options follow @sanity/visual-editing's stability policy rather than this package's: they can change in a minor release of that dependency without a corresponding @sanity/astro release, so pin it if you rely on them.
The parameter types for these callbacks (HistoryAdapter, HistoryAdapterNavigate, HistoryRefresh, HistoryUpdate, OverlayComponentResolver, OverlayPluginDefinition, SuspiciousStegaReport, and VisualEditingOptions itself) are re-exported from @sanity/astro/visual-editing/component, along with RefreshStrategy and VisualEditingComponentProps (VisualEditingOptions plus experimental_refreshStrategy).
2. Add the Presentation tool to the Studio
Follow the instructions on how to configure the Presentation tool.
3. Enable Stega
If you already run Studio on an Astro route, then you can set the stega.studioUrl to the same relative path:
export default defineConfig({
integrations: [
sanity({
studioBasePath: '/admin',
stega: {
studioUrl: '/admin',
},
}),
],
})Now, all you need is a loadQuery helper function akin to this one:
// load-query.ts
import {type QueryParams} from 'sanity'
import {sanityClient} from 'sanity:client'
const visualEditingEnabled = import.meta.env.PUBLIC_SANITY_VISUAL_EDITING_ENABLED === 'true'
const token = import.meta.env.SANITY_API_READ_TOKEN
export async function loadQuery<QueryResponse>({
query,
params,
}: {
query: string
params?: QueryParams
}) {
if (visualEditingEnabled && !token) {
throw new Error(
'The `SANITY_API_READ_TOKEN` environment variable is required during Visual Editing.',
)
}
const perspective = visualEditingEnabled ? 'drafts' : 'published'
const {result, resultSourceMap} = await sanityClient.fetch<QueryResponse>(query, params ?? {}, {
filterResponse: false,
perspective,
resultSourceMap: visualEditingEnabled ? 'withKeyArraySelector' : false,
stega: visualEditingEnabled,
...(visualEditingEnabled ? {token} : {}),
useCdn: !visualEditingEnabled,
})
return {
data: result,
sourceMap: resultSourceMap,
perspective,
}
}You'll notice that we rely on a "read token" which is required in order to enable stega encoding and for authentication when Sanity Studio is live previewing your application.
- Go to https://sanity.io/manage and select your project.
- Click on the 🔌 API tab.
- Click on + Add API token.
- Name it "SANITY_API_READ_TOKEN" and set Permissions to Viewer and hit Save.
- Copy the token and add it to your
.env.localfile:SANITY_API_READ_TOKEN="<paste your token here>"
Now, you can query and interact with stega-enabled data using the visual editing overlays:
// some.astro file
import {loadQuery} from '../load-query'
const {data: movies} = await loadQuery<Array<{title: string}>>({
query: `*[_type == 'movie']`,
})Examples
The apps folder holds runnable examples. Each one reads published content from a hosted Sanity dataset, so it runs without an API token unless noted.
| App | Shows | Run from the repo root |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- |
| apps/minimal | The smallest setup: one page that fetches with sanity:client. No Studio, no React | pnpm dev:minimal |
| apps/example | Blog with Portable Text, images and an embedded Studio, on Astro 5 | pnpm dev:example |
| apps/example-latest | The same blog on the newest Astro and Sanity releases | pnpm dev:example-latest |
| apps/example-ssr | The blog rendered on the server with the Vercel adapter | pnpm dev:example-ssr |
| apps/cinema | A static site on Astro 7 with content collections loaded through sanityLoader, an embedded Studio and Tailwind CSS | pnpm dev:cinema |
| apps/movies | Server rendering, Visual Editing and the Presentation tool. Needs SANITY_API_READ_TOKEN; see the app README | pnpm dev:movies |
| apps/observatory | A reference implementation of advanced Sanity features (sync tag caching, draft preview, Visual Editing) on Astro 7, built without @sanity/astro. Its Studio is apps/observatory-studio and its Sanity Function is in apps/observatory-functions | pnpm dev:observatory |
