Top-Level Await Requirements
You'll learn: The specific conditions your JavaScript environment must meet before you can use top-level await.
The Module Requirement
Top-level await isn't available everywhere in JavaScript—it only works in ES modules. This is a hard requirement, not a suggestion. If you try using await at the top level in a regular script, you'll get a syntax error.
Think of it like needing a passport to cross certain borders. Top-level await requires the "ES module passport" to function.
In Browser Environments
When writing JavaScript for browsers, you must explicitly declare your script as a module:
<script type="module" src="app.js"></script>
Without type="module", the browser treats your code as a regular script, and top-level await will fail. Inside app.js, you can now use await directly:
// This works in app.js because it's loaded as a module
const data = await fetch('/api/config').then(r => r.json());
console.log(data);
In Node.js Environments
Node.js requires one of two signals to recognize an ES module:
- Use the
.mjsfile extension instead of.js - Add
"type": "module"to your package.json
Without either signal, Node treats your file as a CommonJS module, where top-level await isn't allowed.
Why the Restriction?
ES modules have a different loading and evaluation model than regular scripts. Top-level await needs this module system to properly coordinate dependencies and asynchronous initialization across multiple files.
Key Takeaway: Top-level await requires ES module mode—use type="module" in browsers or .mjs (or package.json configuration) in Node.js. Without this, your await statement will trigger a syntax error.