Use Sanity with Astro

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:

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's output is '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, and clients.default is the client exported as sanityClient. Requires @sanity/astro 3.6.0 or later.
  • logClientRequests ('dev', 'build', or 'always'): logs each server-side request made through a sanity:client client, with its duration, query, and calling file. 'dev' logs in the development server, 'build' logs in production (during astro build and 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 the sanity:client and sanity:studio modules for you, so env.d.ts doesn't need a reference to @sanity/astro/module. Requires Astro 4.14 or later. Defaults to false.
  • env (object): names of the environment variables to read projectId and dataset from when the server runs, for example { projectId: 'SANITY_PROJECT_ID', dataset: 'SANITY_DATASET' }, so one build can serve several projects or datasets. Applies to sanityClient in server code rendered on demand and to the embedded studio with browser history. Prerendered pages, sanityLoader, browser code, other named clients, and the embedded studio with hash history keep the build-time values. Requires @sanity/astro 4.0.0 or later and Astro 5 or later. With browser history, the embedded studio must export a single workspace from sanity.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-standalone to use it. Requires @sanity/astro 4.0.0 or later. Defaults to false. If your project also uses @astrojs/react, the overlays ship a second copy of React, and the integration logs a warning. With experimental_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/astro README for the options. Requires @sanity/astro 4.0.0 or later.

The sanity:client virtual module

Once configured, the integration exposes a pre-configured Sanity client through a virtual module:

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):

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:

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:

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:

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'): set useCdn: 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'): set useCdn: true for published content. The CDN reduces latency for repeated queries. Set it to false when fetching draft content with a token.
  • Mixed static and server rendering: Astro 5 removed the output: 'hybrid' mode. Use output: 'static' or output: 'server' and opt individual pages in or out with export const prerender = true or export const prerender = false. Set useCdn to match the rendering mode of each page: false for prerendered pages, true for server-rendered pages fetching published content.

Minimal working configuration

Here's the smallest setup that works for a statically generated Astro site:

From here, you can import sanityClient in any .astro file and start querying content.

Was this page helpful?