How to Delete All Assets That Aren't Used After Development

2 replies
Last updated: Sep 27, 2021
During development I needed to add a lot of assets that are not necessary any longer. Is there a way to delete all assets that aren't currently used?
AI Update

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:

  1. Create a file called deleteUnusedAssets.js in 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)
    }
  })
  1. Run it with:
sanity exec deleteUnusedAssets.js --with-user-token

Important: 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.

Hi
user T
, this snippet should let you do exactly that πŸ™‚ https://github.com/sanity-io/sanity-recipes/blob/master/snippets/deleteUnusedAssets.js
Works like a charm. 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?