Gatsby - How to Filter a List of Documents by Whether they are Published or Not
The easiest way to filter out draft documents from your queries is to add a filter condition that excludes any document with an _id starting with drafts.. Here's how:
*[_type == 'yourDocType' && !(_id in path("drafts.**"))]The !(_id in path("drafts.**")) part filters out any document whose ID matches the pattern drafts.*, which is how Sanity identifies draft documents.
Understanding how drafts work:
In Sanity's Content Lake, drafts and published documents are stored as separate entities. When you edit a published document, Sanity creates a copy with the ID prefixed by drafts. (e.g., drafts.asdf-1234). So you might have both asdf-1234 (published) and drafts.asdf-1234 (draft) in your dataset at the same time.
Alternative approach using perspectives:
Instead of manually filtering, you can also use the published perspective when querying via the API. As of the recent API version v2025-02-19, the default perspective is now published, which automatically returns only published documents. If you're still getting drafts, you might be using an older API version or explicitly setting a different perspective.
You can set the perspective in your client configuration:
const client = createClient({
// ... other config
perspective: 'published', // Only returns published documents
useCdn: true
})The published perspective is perfect for production environments where you only want live content, while previewDrafts is useful for preview environments where you want to see unpublished changes.
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.