Top-level await fails in sanity.config.ts build with esbuild target error
This is a known issue with Sanity Studio's build process! The error occurs because Vite (which Sanity Studio uses for building) has esbuild configured with a target that doesn't support top-level await by default during production builds, even though it works fine in development.
The solution is to configure Vite to use a newer build target that supports top-level await. You can do this in your sanity.cli.ts (or sanity.cli.js) file by extending the Vite configuration:
import { defineCliConfig } from 'sanity/cli';
export default defineCliConfig({
api: {
projectId: '<PROJECT_ID>',
dataset: '<DATASET>',
},
vite: config => {
return {
...config,
build: {
...config.build,
target: 'esnext',
},
};
},
});This tells Vite to target esnext during the build process, which includes support for top-level await. The key is that you're overriding the build.target setting while preserving the rest of Vite's default configuration.
As you mentioned, using top-level await in sanity.config.ts for things like fetching the current user is actually a valid pattern that Sanity team members have recommended, so you're not doing anything wrong! The issue is just that the default build target needs to be adjusted to support this modern JavaScript feature.
After making this change, your npm run build should work without throwing the "Top-level await is not available" error. This solution comes directly from a community answer on the same issue, where it successfully resolved the problem for other developers.
Show original thread7 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.