How to get only published results in GROQ?
To get only published documents in your GROQ queries, you have a few options depending on your API version:
If you're using API version 2025-02-19 or later (released February 24, 2025), the default perspective is already set to published, so your queries will automatically return only published documents. No changes needed!
If you're using an older API version, you need to explicitly set the perspective parameter. Here's how:
// Using the client
const query = '*[_type == "post"]'
const params = {}
const options = { perspective: 'published' }
const posts = await client.fetch(query, params, options)Or when configuring your client:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
apiVersion: '2025-02-19', // Use latest API version
perspective: 'published', // Explicitly set to published
useCdn: true
})Alternative: Filter in your GROQ query
You can also filter out drafts directly in your GROQ query:
*[_type == "post" && !(_id in path("drafts.**"))]This filters out any documents whose _id starts with drafts., leaving you with only published documents.
The API version 2025-02-19 documentation explains that the default perspective changed from raw (which includes drafts, published, and versions) to published specifically to make this easier. If you upgrade to the latest API version, you'll get published-only results by default!
Show original thread3 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.