Prevent user from deleting a document in Sanity
Yes! You can prevent users from deleting specific documents (like singletons) by filtering out the delete action using a custom document actions resolver. This is perfect for protecting configuration documents that should never be deleted.
Here's how to set it up in your studio configuration:
// sanity.config.ts (or .js)
import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
export default defineConfig({
// ... other config
document: {
actions: (prev, context) => {
const singletons = ['siteSettings', 'navigation', 'homepage']
// For singleton documents, remove delete, duplicate, and unpublish actions
if (singletons.includes(context.schemaType)) {
return prev.filter(
(action) => !['delete', 'duplicate', 'unpublish'].includes(action.action)
)
}
return prev
}
}
})This approach:
- Filters out the delete action (and optionally duplicate/unpublish) for specific document types
- Keeps all other actions like publish and discard available
- Works perfectly for singletons configured at build time
For more granular control, you can also filter based on other conditions:
actions: (prev, context) => {
// Check document ID instead of type
if (context.documentId === 'siteConfig') {
return prev.filter((action) => action.action !== 'delete')
}
// Or check if it's a published document
if (context.currentUser?.role === 'editor' && context.published) {
return prev.filter((action) => action.action !== 'delete')
}
return prev
}Important note: This only removes the delete button from the Studio UI. For true protection, you should also set up access control with custom roles to prevent deletion at the API level. Otherwise, users could still delete documents via API calls or GROQ queries.
For production environments with sensitive configuration documents, combine both approaches: filter the UI actions for better UX and enforce permissions via custom roles for security. Custom roles (available on Enterprise plans) let you define granular permissions including restricting delete operations at the permission level, ensuring documents are protected even from API access.
Show original thread2 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.