How to detect if document is draft in Sanity schema preview?

3 replies
Last updated: Apr 23, 2020
Is there any way in schema > preview to know if it is a draft or not?
AI Update

Yes! You can determine if a document is a draft in the schema's preview configuration by checking the _id field. Since draft documents have an _id that starts with drafts., you can use this to detect draft status.

Here's how to implement it:

preview: {
  select: {
    title: 'title',
    documentId: '_id'
  },
  prepare({title, documentId}) {
    const isDraft = documentId.startsWith('drafts.')
    
    return {
      title: title,
      subtitle: isDraft ? 'Draft' : 'Published'
    }
  }
}

You can also use this to add visual indicators like emojis:

preview: {
  select: {
    title: 'title',
    theId: '_id'
  },
  prepare(selection) {
    const {title, theId} = selection
    const isDraft = theId.startsWith('drafts.')
    const icon = isDraft ? '👷' : '✅'
    
    return {
      title: title,
      media: <span style={{fontSize: '1.5rem'}}>{icon}</span>
    }
  }
}

The key is selecting the _id field in your select object, then checking if it starts with 'drafts.' in the prepare function. As explained in the draft documents documentation, all draft documents have an _id prefixed with drafts., while published documents have the regular _id without this prefix.

This approach works because draft and published documents are stored as separate entities in your dataset, with the draft version always maintaining the drafts. prefix until it's published.

Show original thread
3 replies
You could check whether the
_id
string starts with
drafts.
. A bit further down this page there’s an example of using
preview
with
prepare
to perform some logic with your selection of preview fields: https://www.sanity.io/docs/previews-list-views#specify-preview-options-857e5d82a2d3
Let me know if that’s enough to get going
🙂
Thanks, it worked!
Great, Jørgen! Thanks for confirming 🎉

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?