To use Astro with Sanity, install the official @sanity/astro integration, add your project ID and dataset to astro.config.mjs, and import the preconfigured client from sanity:client to run GROQ queries in page frontmatter. For a static site, generate pages with getStaticPaths() and trigger a rebuild from a Sanity webhook whenever editors publish.
This guide covers the full Astro Sanity setup on Astro 7: installation, queries, dynamic routes, rich text, images, the embedded Studio, and how to keep the site fresh.
Key Takeaways
npx astro add @sanity/astroinstalls the integration;@astrojs/reactis only needed if you embed Studio.- Import
sanityClientfrom thesanity:clientvirtual module anywhere in server code.- Static output plus a Sanity webhook to your host’s deploy hook is the simplest, fastest setup.
- Render Portable Text with a component library and images through Sanity’s CDN URL parameters.
- On-demand pages show new content instantly but cost a request to Sanity per page view unless cached.
Why pair Astro with Sanity
Sanity is a hosted, API-first content platform. Content lives in Sanity’s Content Lake, editors work in Sanity Studio (a React app you configure in code), and your site fetches content over an API with GROQ, Sanity’s query language.
Astro is a good consumer for that API. Queries run on the server at build time, so the browser receives finished HTML with no CMS SDK, and editors get a structured editing environment instead of Markdown files. The trade-off against a Git-based CMS is a third-party dependency and usage-based pricing on Sanity’s side; the headless CMS guide compares Sanity with other options.
Step 1: Install the Astro Sanity integration
If you don’t have a Sanity project yet, create one with npm create sanity@latest (it can also scaffold a standalone Studio). Note the project ID and dataset name. Then add the integration to your Astro project:
npx astro add @sanity/astro @astrojs/react
Skip @astrojs/react if you’ll run Studio separately. Configure the integration:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import sanity from '@sanity/astro';
import react from '@astrojs/react';
export default defineConfig({
site: 'https://www.example.com',
integrations: [
sanity({
projectId: 'your-project-id',
dataset: 'production',
apiVersion: '2025-01-01',
useCdn: false,
}),
react(),
],
});
The integration accepts the same options as @sanity/client. Set useCdn: false for static builds so each build reads the freshest published content; set it to true for on-demand pages where speed matters more than a few seconds of staleness. Pin apiVersion to a date so query behavior doesn’t change under you.
In Sanity’s project settings, add your local dev URL (http://localhost:4321) and production URL as CORS origins if you’ll query from the browser or embed Studio.
Step 2: Query Sanity with GROQ
Import the client from the sanity:client virtual module and call fetch with a GROQ query:
---
// src/pages/blog/index.astro
import { sanityClient } from 'sanity:client';
const posts = await sanityClient.fetch(`
*[_type == "post" && defined(slug.current)] | order(publishedAt desc) {
title,
"slug": slug.current,
excerpt,
publishedAt
}
`);
---
<h1>Blog</h1>
<ul>
{posts.map((post) => (
<li>
<a href={`/blog/${post.slug}/`}>{post.title}</a>
<p>{post.excerpt}</p>
</li>
))}
</ul>
GROQ projections (the { ... } block) return only the fields you ask for, and "slug": slug.current flattens nested values. That keeps responses small and the template code simple.
For TypeScript, add the integration’s types to src/env.d.ts so sanity:client resolves:
// src/env.d.ts
/// <reference types="@sanity/astro/module" />
Sanity’s TypeGen (npx sanity typegen generate) can generate types for your schema and queries if you want full type safety on results.
Step 3: Build static pages with getStaticPaths
For one page per post, fetch the slugs and full documents in getStaticPaths():
---
// src/pages/blog/[slug].astro
import { sanityClient } from 'sanity:client';
import BaseLayout from '../../layouts/BaseLayout.astro';
import PortableText from '../../components/PortableText.astro';
export async function getStaticPaths() {
const posts = await sanityClient.fetch(`
*[_type == "post" && defined(slug.current)] {
title,
"slug": slug.current,
excerpt,
body,
"image": mainImage.asset->url,
"imageAlt": mainImage.alt
}
`);
return posts.map((post) => ({ params: { slug: post.slug }, props: { post } }));
}
const { post } = Astro.props;
---
<BaseLayout title={post.title} description={post.excerpt}>
<article>
<h1>{post.title}</h1>
{post.image && (
<img
src={`${post.image}?w=1200&h=630&fit=crop&auto=format`}
alt={post.imageAlt ?? ''}
width="1200"
height="630"
/>
)}
<PortableText value={post.body} />
</article>
</BaseLayout>
One query fetches everything, and Astro renders every page at build time. If you have thousands of documents, this is still one API call, which is gentler on usage limits than one call per page. The getStaticPaths guide explains params and props in detail.
Rendering Portable Text and images
Sanity stores rich text as Portable Text, a JSON array of blocks. The community package astro-portabletext renders it to HTML with Astro components:
npm install astro-portabletext
---
// src/components/PortableText.astro
import { PortableText as PT } from 'astro-portabletext';
const { value } = Astro.props;
---
<div class="prose">
<PT value={value} />
</div>
You can pass a components prop to map custom block types (code blocks, callouts, embedded images) to your own Astro components.
For images, Sanity’s asset CDN resizes on the fly through URL parameters: w, h, fit, auto=format and others. Requesting the size you display, as in the example above, keeps pages light. The @sanity/image-url package builds the same URLs from image references with hotspot and crop support if you need it. To use Astro’s <Image /> component with remote Sanity URLs instead, allow the domain in config:
// astro.config.mjs (excerpt)
image: {
domains: ['cdn.sanity.io'],
},
Without that entry, Astro won’t optimize the remote image; see the remote image not allowed fix.
Embedding Sanity Studio in Astro
Studio can live at a path on your site instead of a separate deployment. Add studioBasePath to the integration and a sanity.config.ts at the project root:
// astro.config.mjs (excerpt)
sanity({
projectId: 'your-project-id',
dataset: 'production',
apiVersion: '2025-01-01',
useCdn: false,
studioBasePath: '/studio',
}),
// sanity.config.ts
import { defineConfig } from 'sanity';
import { structureTool } from 'sanity/structure';
import { schemaTypes } from './src/sanity/schemaTypes';
export default defineConfig({
projectId: 'your-project-id',
dataset: 'production',
plugins: [structureTool()],
schema: { types: schemaTypes },
});
Studio is a client-side React app. On a fully static site, its sub-routes (/studio/structure/post) need a rewrite on your host that sends /studio/* to the Studio page; with an adapter and on-demand rendering, the integration handles the catch-all route itself. Many teams simply deploy Studio separately with npx sanity deploy and keep the Astro site lean.
Keeping a static Astro Sanity site fresh
A static build shows content as it was at build time. To publish new content without a developer:
- In your host, create a deploy hook. Cloudflare Pages, Netlify and Vercel each give you a URL that starts a build when it receives a POST.
- In Sanity’s project settings, add a webhook for create, update and delete events on published documents, pointing at that URL.
- Optionally filter the webhook to the document types your site renders, so editing an unrelated document doesn’t rebuild.
Builds of a typical content site take well under a few minutes, so editors see changes shortly after publishing. The deploy guide and the Cloudflare Pages docs cover setting up the build itself.
Static or on-demand: which suits your Sanity site
| Static + webhook | On-demand pages | |
|---|---|---|
| New content appears | After the rebuild finishes | Immediately |
| Sanity API calls | One set per build | One per uncached page view |
| Hosting | Any static host | Needs an adapter |
| Page speed | Fastest (pre-built HTML) | Depends on query time and caching |
| Preview drafts | Separate preview deployment | Possible with a token and a draft perspective |
For on-demand pages, add an adapter and export const prerender = false to the routes that need live data. Cache responses with a Cache-Control header so repeated views don’t each hit Sanity. The Astro SSR guide explains the setup.
Sanity also offers visual editing through its Presentation tool, which overlays click-to-edit controls on your live site. It requires on-demand rendering for draft content and extra setup described in Sanity’s Astro documentation.
Using Sanity with an Astro theme
Most Astro themes, including every Komal theme, read content from local content collections. Switching a theme to Sanity means replacing getCollection() calls with GROQ queries that return the same shape, which is usually a contained change to a handful of pages. Match your Sanity schema to the fields the theme’s components expect (title, description, date, image, body) and the layouts work unchanged. Browse the Astro themes if you want a finished front end to connect to your Sanity project.
FAQ
Is Sanity free to use with Astro?
Sanity has a free plan with usage limits on documents, API requests and users, and paid plans above it. Check Sanity’s pricing page for current limits. The @sanity/astro integration itself is free and open source.
Do I need React to use Sanity with Astro?
Only if you embed Sanity Studio inside the Astro site, because Studio is a React app. Fetching and rendering content needs no React; the client runs in Astro’s server code and outputs plain HTML.
How do I rebuild my Astro site when content changes in Sanity?
Create a deploy hook on your host and add it as a Sanity webhook that fires on publish, update and delete. Each event starts a fresh build that fetches the latest content.
Can I use Sanity with Astro content collections?
Yes, with a custom loader that calls sanityClient.fetch and stores each document, so pages use getCollection() as if the content were local. Many sites skip this and query Sanity directly in pages, which is simpler for a single source.
Should I set useCdn to true or false?
Use false for static builds so each build reads the latest published content. Use true for on-demand pages where faster, cached responses matter more than a short delay in freshness.