Next.js Conf 2024: Your app should be Live by Default – Watch Keynote

Top-level await not available in build environment for Sanity config file

7 replies
Last updated: Jun 6, 2023
I’m using a top-level await to get the current user in my sanity.config.ts and it works fined in dev but throws “Top-level await is not available in the configured target environment ” when
npm run build
. I don’t know if there is a way to configure the targets that are used by esbuild. The top level await was actually recommended by a sanity member so it doesn’t seem like I’m doing something non-canon here.
Jun 6, 2023, 6:09 PM
have you tried using a third party lib like axios https://www.npmjs.com/package/axios
Jun 6, 2023, 6:12 PM
to what end?
Jun 6, 2023, 6:12 PM
well i find that using vanilla await with node has issues and this tool has a tendency to work when await does not.
Jun 6, 2023, 6:13 PM
This doesn’t make any sense, sorry. The top level await does work. It’s the build tool that is the problem as it’s disabled on a feature level
Jun 6, 2023, 6:14 PM
user B
What about this in your
sanity.cli.ts
file?

import { defineCliConfig } from 'sanity/cli';

export default defineCliConfig({
  api: {
    projectId: '<PROJECT_ID>',
    dataset: '<DATASET>',
  },
  vite: config => {
    return {
      ...config,
      build: {
        ...config.build,
        target: 'esnext',
      },
    };
  },
});
Jun 6, 2023, 6:15 PM
You’re the best! Works
Jun 6, 2023, 6:17 PM
Great! Glad to hear it. Full credit to a colleague of mine who I swiped it from. 🤫
Jun 6, 2023, 6:18 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?