What Is Top-Level Await?
You'll learn how await can now be used directly in ES modules, without wrapping it in an async function.
The Core Idea
Until now, every time you've used await, it's been inside an async function — that was the rule. But in modern JavaScript (ES2022+), top-level await lets you use await directly at the top level of an ES module (a file that uses import/export). No async wrapper needed.
Think of it like removing a layer of scaffolding: instead of building a temporary structure (an async function) just to wait for something, you can wait directly where you need to.
Why This Matters
Before top-level await, if you wanted to await something when a module loaded, you had to do awkward workarounds:
// Old way: wrap in an async IIFE
(async () => {
const data = await fetch('/api/config');
export const config = await data.json(); // Can't export here!
})();
With top-level await, modules can simply wait:
// New way: direct await in module scope
const data = await fetch('/api/config');
export const config = await data.json(); // Clean and direct
Important Constraint
Top-level await only works in ES modules (files with type="module" in browsers, or .mjs files / "type": "module" in Node.js). It doesn't work in regular scripts or CommonJS modules.
When a module uses top-level await, any module importing it will wait for those awaits to complete before continuing.
Key Takeaway: Top-level await lets you use await directly in ES module scope, eliminating the need to wrap it in async functions for module initialization logic.