
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeThis is indeed a JavaScript/TypeScript limitation when using sanity exec. The error occurs because you're using top-level await outside of an async function context.
The fix is straightforward: wrap your code in an async function. Here's your corrected script:
import { getCliClient } from 'sanity/cli';
const client = getCliClient().withConfig({ apiVersion: '2023-05-24' })
const loadCategories = async () => {
const categories = await client.fetch('*[_type == "category"]');
categories.forEach(category => {
console.log(category)
});
}
// Wrap in an async function
(async () => {
try {
await loadCategories();
} catch (error) {
console.error(error);
}
})();This creates an immediately-invoked async function expression (IIFE) that can use await internally. This is the standard pattern for migration scripts run with sanity exec.
Alternative: Use the migration tooling
If you're doing content migrations specifically, consider using Sanity's built-in migration tooling instead, which is the recommended approach. It provides several advantages:
Create a migration script with:
npx sanity@latest migration createThe migration tooling is specifically designed for content transformations and handles many of the complexities automatically. However, sanity exec with the IIFE pattern works perfectly fine for simpler scripts or one-off operations!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store