How to Delete All Assets That Aren't Used After Development
Yes, there's a script you can use to delete all unused assets from your dataset! Sanity has an official recipe that does exactly this.
The script works by using a GROQ query to find all image and file assets that have zero references from other documents (sometimes called "orphaned" assets), then deletes them in a transaction. Here's how to use it:
- Create a file called
deleteUnusedAssets.jsin your project with this code:
// This script will find and delete all assets that are not
// referenced (in use) by other documents.
//
// Run with: sanity exec deleteUnusedAssets.js --with-user-token
import {getCliClient} from 'sanity/cli'
const client = getCliClient({apiVersion: '2024-01-01'})
const query = `
*[_type in ["sanity.imageAsset", "sanity.fileAsset"]]
{_id, "refs": count(*[references(^._id)])}
[refs == 0]
._id
`
client
.fetch(query)
.then(ids => {
if (!ids.length) {
console.log('No assets to delete')
return true
}
console.log(`Deleting ${ids.length} assets`)
return ids
.reduce((trx, id) => trx.delete(id), client.transaction())
.commit({visibility: 'async'})
.then(() => console.log('Done!'))
})
.catch(err => {
if (err.message.includes('Insufficient permissions')) {
console.error(err.message)
console.error('Did you forget to pass `--with-user-token`?')
} else {
console.error(err.stack)
}
})- Run it with:
sanity exec deleteUnusedAssets.js --with-user-tokenImportant: It's highly recommended to export your dataset as a backup before running this script, since it permanently deletes data. The script uses the --with-user-token flag to ensure you have the proper permissions to delete assets.
The GROQ query count(*[references(^._id)]) checks how many documents reference each asset, and filters to only those with zero references before building a transaction to delete them all.
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.