Error with top-level await while running data migration script
This 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:
- Automatic batching of mutations to avoid rate limits
- Dry-run mode by default with visual feedback
- Better abstractions for document operations
- Built-in validation against your schema
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 – 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.