Deleting documents with @sanity/client
Learn how to delete documents by ID or by query using the Sanity JavaScript client.
The @sanity/client library provides methods for deleting documents individually by ID or in bulk using a query. This guide covers both approaches.
Prerequisites
Deleting requires an authenticated client with a write token. See Getting started with @sanity/client for setup instructions.
Delete by ID
Use client.delete() to remove a single document by its ID:
import {ClientError} from '@sanity/client'
// Delete a single document
const result = await client.delete('post-123')
console.log('Deleted document:', result.documentIds[0])
// Delete a draft document
await client.delete('drafts.post-456')
// Delete with error handling
try {
await client.delete('post-789')
console.log('Document deleted successfully')
} catch (error) {
if (error instanceof ClientError && error.statusCode === 404) {
console.log('Document not found')
} else {
const message = error instanceof Error ? error.message : String(error)
console.error('Delete failed:', message)
}
}Delete by query
To delete every document that matches a GROQ query in one request, pass an object with a query and optional params to client.delete(). This is the recommended way to delete by query. A single query-based mutation affects at most 10,000 documents:
const result = await client.delete({
query: '*[_type == "post" && publishedAt < $cutoffDate]',
params: {cutoffDate: '2020-01-01'},
})
console.log(`Deleted ${result.documentIds.length} documents`)To review the matching documents before you delete them, fetch their IDs first, then delete them in a transaction. All deletions in a transaction succeed or fail together:
// Query for the IDs of documents to delete
const query = '*[_type == "post" && publishedAt < $cutoffDate]{_id}'
const params = {cutoffDate: '2020-01-01'}
const docsToDelete = await client.fetch<{_id: string}[]>(query, params)
if (docsToDelete.length === 0) {
console.log('No documents to delete')
} else {
// Build transaction with all deletions
const transaction = docsToDelete.reduce(
(tx, doc) => tx.delete(doc._id),
client.transaction()
)
// Execute the transaction
const result = await transaction.commit()
console.log(`Deleted ${result.results.length} documents`)
}Always test your query before deleting. Use client.fetch() to verify which documents match your query, then proceed with deletion. Deleted documents can be restored from document history only within your plan's history retention period. After that, you need a backup.
The fetch-then-delete example uses client.transaction() to delete all matching documents atomically. Learn more about transactions in Transactions.
Was this page helpful?
Feedback submitted, thanks for helping us improve the docs. Have you tried these alternatives?