Gatsby - How to Filter a List of Documents by Whether they are Published or Not

3 replies
Last updated: Feb 2, 2022
Hey, does anyone know how to filter a list of documents from Sanity by whether they are published or not? Currently I get all of them whether they’re draft or not.
AI Update

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.

in the plugin options for
gatsby-source-sanity
in
gatsby-config.js
you can set
overlayDrafts
to true/false to include or exclude draft documents. Typically one might set it to an env variable so you get drafts while testing, but not in production or whatever your preference:
{
      resolve: "gatsby-source-sanity",
      options: {
        projectId: "abc123",
        dataset: "production",
        watchMode: isDev,
        overlayDrafts: isDev,
        token: process.env.MY_SANITY_TOKEN,
      },
},

There is an example GROQ query here on how to not return items marked as draft, https://www.sanity.io/docs/drafts#ebfb408fa9b6
user N
Thank you, that’s perfect. Completely forgot about that option!

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.

Was this answer helpful?