Configuring @sanity/astro
Reference for Sanity integration configuration in Astro. Covers integration options, the sanity:client virtual module, environment variables, type declarations, and creating additional client instances.
Configure the integration in your astro.config.mjs file. The integration accepts the same options as @sanity/client, plus additional integration-specific options:
import sanity from '@sanity/astro'
import { defineConfig } from 'astro/config'
export default defineConfig({
integrations: [
sanity({
projectId: 'YOUR_PROJECT_ID',
dataset: 'production',
apiVersion: '2026-03-01',
useCdn: false,
}),
],
})Configuration options
The integration accepts these options:
projectId(string): your Sanity project ID. Find it at sanity.io/manage.dataset(string): the dataset to query. Typically "production".apiVersion(string): API version date string, for example '2026-03-01'. Required for predictable query behavior.useCdn(boolean): whether to use the Sanity CDN. Set to false for static builds, true for server-rendered pages.token(string): API token for authenticated requests. Required for draft content and Visual Editing. Never hardcode tokens; use environment variables.studioBasePath(string): route path for the embedded studio, for example '/admin'. Requires@astrojs/react.studioRouterHistory('browser'or'hash'): how the embedded studio routes. Defaults to'hash'when Astro'soutputis'static', and'browser'otherwise. Browser history needs a server adapter; hash history works with static output.stega(object): stega encoding configuration for Visual Editing.clients(object): named client configurations for reading from more than one project or dataset. Each entry takes the same options as@sanity/client, andclients.defaultis the client exported assanityClient. Requires @sanity/astro 3.6.0 or later.logClientRequests('dev','build', or'always'): logs each server-side request made through asanity:clientclient, with its duration, query, and calling file.'dev'logs in the development server,'build'logs in production (duringastro buildand in a server-rendered production deployment), and'always'logs in both. Logging is off when this option isn't set.injectTypes(boolean): registers the type declarations for thesanity:clientandsanity:studiomodules for you, soenv.d.tsdoesn't need a reference to@sanity/astro/module. Requires Astro 4.14 or later. Defaults tofalse.env(object): names of the environment variables to readprojectIdanddatasetfrom when the server runs, for example{ projectId: 'SANITY_PROJECT_ID', dataset: 'SANITY_DATASET' }, so one build can serve several projects or datasets. Applies tosanityClientin server code rendered on demand and to the embedded studio withbrowserhistory. Prerendered pages,sanityLoader, browser code, other named clients, and the embedded studio withhashhistory keep the build-time values. Requires@sanity/astro4.0.0 or later and Astro 5 or later. Withbrowserhistory, the embedded studio must export a single workspace fromsanity.config.ts; an array of workspaces throws an error.visualEditingStandalone(boolean): runs the Visual Editing overlays on@sanity/visual-editing-standalone, a self-contained build with its own React, React DOM, and styled-components. Install@sanity/visual-editing-standaloneto use it. Requires@sanity/astro4.0.0 or later. Defaults tofalse. If your project also uses@astrojs/react, the overlays ship a second copy of React, and the integration logs a warning. Withexperimental_refreshStrategy="in-place", edits aren't patched into the page's text instantly in this mode; the in-place morph and the default reload still run.experimental_live(object): experimental. Generates typed loaders and Zod schemas for Astro live collections (Astro 6 and later) from your Sanity schema. Nothing is extracted or generated unless you set it. See Live collections in the@sanity/astroREADME for the options. Requires@sanity/astro4.0.0 or later.
The sanity:client virtual module
Once configured, the integration exposes a pre-configured Sanity client through a virtual module:
---
import { sanityClient } from 'sanity:client'
const posts = await sanityClient.fetch(
`*[_type == "post" && defined(slug)] | order(publishedAt desc)`
)
---This client uses the options you provided in astro.config.mjs. You can use it in any .astro component's frontmatter, in API routes, or in server-side scripts.
Adding type declarations
To get TypeScript support for the sanity:client module, add a reference to your env.d.ts file (typically in your src directory):
/// <reference types="astro/client" /> /// <reference types="@sanity/astro/module" />
After updating this file, restart your TypeScript language server (or restart your editor) for the types to resolve.
On Astro 4.14 and later, you can set injectTypes: true in the integration options instead, and the integration registers these declarations through Astro's type generation. The manual reference keeps working either way.
Environment variables
Store sensitive values like project IDs and tokens in environment variables rather than hardcoding them in your config. Create a .env file in your project root:
PUBLIC_SANITY_PROJECT_ID="YOUR_PROJECT_ID" PUBLIC_SANITY_DATASET="production" SANITY_API_READ_TOKEN="your-read-token"
Astro uses the PUBLIC_ prefix convention to distinguish client-side and server-side variables. Variables with the prefix are safe to expose to the browser. Never prefix tokens with PUBLIC_, as this would expose them in client-side JavaScript.
Creating additional client instances
The sanityClient export works well for most use cases. To read from more than one project or dataset, configure named clients with the clients option (@sanity/astro 3.6.0 or later). Each entry takes the same options as @sanity/client, and 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: 'production',
apiVersion: '2026-03-01',
useCdn: false,
},
community: {
projectId: 'YOUR_COMMUNITY_PROJECT_ID',
dataset: 'production',
apiVersion: '2026-03-01',
useCdn: true,
},
},
}),
],
})Top-level client options such as projectId and dataset still configure the default client. You can combine them with clients only when clients has no default entry of its own. Otherwise, the integration throws an error.
Import getClient from sanity:client to read from a named client. sanityClient is still the default client:
---
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 isn't configured throws an error. Named clients configured with a token or headers are only available in server code (frontmatter, endpoints, and middleware). In the browser, getClient returns a stand-in for them that throws on first use, so credentials never end up in a client bundle. The default client is shipped to the browser, so keep tokens out of its configuration.
You can also create a client from @sanity/client directly, for example one configured for draft content:
import { createClient } from '@sanity/client'
export const previewClient = createClient({
projectId: import.meta.env.PUBLIC_SANITY_PROJECT_ID,
dataset: import.meta.env.PUBLIC_SANITY_DATASET,
apiVersion: '2026-03-01',
useCdn: false,
token: import.meta.env.SANITY_API_READ_TOKEN,
perspective: 'drafts',
})This is useful when you need to query draft content alongside published content, or when different parts of your application require different API versions or perspectives. Import previewClient only from server code (frontmatter, endpoints, and middleware). Astro only exposes variables with the PUBLIC_ prefix to browser code, so SANITY_API_READ_TOKEN is undefined there and the client can't read drafts.
When to set useCdn
The right useCdn value depends on your rendering mode:
- Static builds (
output: 'static'): setuseCdn: false. Content is fetched once at build time, so CDN caching adds no benefit. You want the freshest data at build time. - Server-rendered (
output: 'server'): setuseCdn: truefor published content. The CDN reduces latency for repeated queries. Set it tofalsewhen fetching draft content with a token. - Mixed static and server rendering: Astro 5 removed the
output: 'hybrid'mode. Useoutput: 'static'oroutput: 'server'and opt individual pages in or out withexport const prerender = trueorexport const prerender = false. SetuseCdnto match the rendering mode of each page:falsefor prerendered pages,truefor server-rendered pages fetching published content.
Minimal working configuration
Here's the smallest setup that works for a statically generated Astro site:
import sanity from '@sanity/astro'
import { defineConfig } from 'astro/config'
export default defineConfig({
integrations: [
sanity({
projectId: 'YOUR_PROJECT_ID',
dataset: 'production',
apiVersion: '2026-03-01',
useCdn: false,
}),
],
})/// <reference types="astro/client" /> /// <reference types="@sanity/astro/module" />
From here, you can import sanityClient in any .astro file and start querying content.