Prevent user from deleting a document in Sanity

2 replies
Last updated: Mar 2, 2024
hey, is there a way to prevent the user from deleting a document? (e.g. a singleton document configured at build time that should be left as is)
AI Update

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 thread
2 replies
Yes, you can remove the action for that document in your config. Here’s how you replace an action. You can adjust it to instead filter out an action.
thanks!

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?