Sanity — Read Content
Query and fetch content from your Sanity dataset using GROQ.
Last updated: 2026-03-29
Install & Configure
Install the Sanity client and use CDN for fast read-only queries.
npm install @sanity/client
// src/lib/sanity.js
import { createClient } from '@sanity/client';
export const client = createClient({
projectId: import.meta.env.PUBLIC_SANITY_PROJECT_ID,
dataset: import.meta.env.PUBLIC_SANITY_DATASET || 'production',
apiVersion: '2024-01-01',
useCdn: true, // CDN for fast reads
});Query with GROQ
Use GROQ queries to fetch documents from your dataset.
// Fetch all published posts
const posts = await client.fetch(
`*[_type == "post" && publishedAt < now()] | order(publishedAt desc) {
_id,
title,
slug,
publishedAt
}`
);
// Fetch a single post by slug
const post = await client.fetch(
`*[_type == "post" && slug.current == $slug][0]`,
{ slug: 'hello-world' }
);Use in Astro Pages
Import the client and query data directly inside your Astro frontmatter.
---
// src/pages/blog/[slug].astro
import { client } from '../../lib/sanity';
const { slug } = Astro.params;
const post = await client.fetch(
`*[_type == "post" && slug.current == $slug][0]`,
{ slug }
);
---
<h1>{post.title}</h1>