Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Delete unused assets

By Espen Hovlandsdal

Script to find and delete unused assets in a dataset


// This script will find and delete all assets that are not
// referenced (in use) by other documents. Sometimes refered
// to as "orphaned" assets.
// Place this script somewhere and run it through
// `sanity exec <script-filename.js> --with-user-token`

/* eslint-disable no-console */
import client from 'part:@sanity/base/client'

const query = `
  *[ _type in ["sanity.imageAsset", "sanity.fileAsset"] ]
  {_id, "refs": count(*[ references(^._id) ])}
  [ refs == 0 ]

  .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())
      .then(() => console.log('Done!'))
  .catch(err => {
    if (err.message.includes('Insufficient permissions')) {
      console.error('Did you forget to pass `--with-user-token`?')
    } else {

This script can be run with sanity exec deleteUnusedAssets.js --with-user-token. It uses a GROQ query to count all incoming references to assets documents and filter out those referred to in another document. It takes the returned array of _ids and builds a transaction of deletions.

It can be wise to export your dataset before running this script since it deletes data.


Other schemas by author

Auto-reload Studio when changes are deployed

Drop this into your Studio to let editors know when there's a more recent version of your Studio available, making sure they have the latest fields and validations.

Go to Auto-reload Studio when changes are deployed