Use Sanity with Astro

Querying content in Astro

Use the @sanity/astro integration to fetch content with GROQ in your Astro components. Covers basic queries, dynamic routes, typed queries, and the loadQuery helper for Visual Editing.

Basic queries

Import the pre-configured client from the sanity:client virtual module and call fetch() in your component's frontmatter:

The client is available in any .astro file's frontmatter, in API routes, and in server-side scripts. Queries use GROQ, Sanity's query language.

Dynamic routes with getStaticPaths

For statically generated pages, use Astro's getStaticPaths to create a page for each document:

Astro calls getStaticPaths at build time and generates one HTML file per route. Content changes require a rebuild to appear on the site.

Parameterized queries

Use GROQ parameters to avoid string interpolation in queries. Pass parameters as the second argument to fetch():

Parameters are sanitized by the client, preventing GROQ injection. Always prefer parameters over template literal interpolation.

Using Sanity TypeGen

For generated types that stay in sync with your schema, use Sanity TypeGen. Define queries with defineQuery in separate .ts files and import them into your Astro components:

Querying references and joins

GROQ supports following references inline with the -> operator:

This fetches the post along with its referenced author and category documents in a single query. For more on GROQ query patterns, see the GROQ documentation.

Typing query results

For basic type safety, use a generic on the fetch() call:

For generated types that stay in sync with your schema, use Sanity TypeGen with defineQuery as shown in the section above.

The loadQuery helper for Visual Editing

When using Visual Editing, queries need additional configuration: a viewer token, the perspective, source maps, and stega encoding. Rather than adding these options to every fetch() call, create a shared loadQuery helper:

Then use it in your components:

The helper transparently switches between published and draft content based on the PUBLIC_SANITY_VISUAL_EDITING_ENABLED environment variable. See Visual Editing for Astro for a full setup.

Was this page helpful?