How to run mutations from Sanity CLI or Vision plugin?
Great question! Yes, there's definitely an easier way than writing a full script for each mutation you want to test.
The sanity exec command is what you're looking for. It lets you run JavaScript/TypeScript files that can perform mutations (create, patch, delete) with access to an authenticated Sanity client.
Here's how it works:
sanity exec myMutation.js --with-user-tokenThe --with-user-token flag gives your script an authenticated client with your user permissions, so you can perform mutations just like you would in your application code.
For quick one-off mutations, you can create simple scripts like:
Create a document:
// createPost.js
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
client.create({
_type: 'post',
title: 'My new post',
slug: {current: 'my-new-post'}
}).then(console.log)Patch a document:
// patchPost.js
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
client.patch('document-id-here')
.set({title: 'Updated title'})
.commit()
.then(console.log)Delete a document:
// deletePost.js
import {getCliClient} from 'sanity/cli'
const client = getCliClient()
client.delete('document-id-here')
.then(console.log)Then run any of these with:
sanity exec createPost.js --with-user-tokenYou can keep a folder of these small utility scripts for common operations you want to test. It's much more convenient than rebuilding a client each time, and the sanity exec command automatically has access to your project configuration.
Pro tip: Always back up your dataset before running mutation scripts, especially on production data:
sanity dataset exportFor more complex bulk operations or migrations, check out the migration tooling which has built-in batching and dry-run capabilities.
Show original thread8 replies
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.