How to detect if document is draft in Sanity schema preview?
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 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.