Sub topic 10
Top-Level Await in ES Modules
This chapter assumes you know ES module import/export syntax and promises with async/await. You should also know how to make a file run as a module in a browser or Node.js, which the earlier chapter on module contexts covered. The earlier chapters used import() inside async functions. Top-level await lets you use await directly in a module's body, outside any function.
What Top-Level Await Is
Top-level await means using the await keyword at the top level of an ES module, outside any function. When the module's code reaches that await, the module pauses its own evaluation until the promise settles. Then it continues from the next statement.
Before this feature existed, await was only valid inside an async function. To run asynchronous setup code in a module, you had to wrap it in one:
// Old style: an async IIFE (immediately invoked function expression)
let config;
(async () => {
const response = await fetch('/config.json');
config = await response.json();
})();
export { config }; // exported while still undefinedThis pattern has a real flaw. The module finishes evaluating straight away, so any module that imports config may read it before the fetch completes. The importer gets undefined and has no promise it can wait on.
With top-level await, the same module looks like this:
// config.js
const response = await fetch('/config.json');
export const config = await response.json();
// main.js
import { config } from './config.js';
console.log(config.apiUrl); // runs only after config.js has finished evaluatingmain.js does not start evaluating until config.js has finished. That includes both awaits. The importer can rely on config being ready without adding any code of its own.
Where It Is Allowed
Top-level await works only in code that the runtime treats as a module. Everywhere else, await outside an async function is a syntax error.
| Context | Top-level await allowed? |
|---|---|
| Browser `<script type="module">` | Yes |
| Browser classic `<script>` | No, SyntaxError |
| Node.js `.mjs` file | Yes |
| Node.js `.js` with `"type": "module"` in package.json | Yes |
| Node.js `.cjs` file, or `.js` without `"type": "module"` | No (see note below) |
| Inside a regular (non-async) function in a module | No, SyntaxError |
| Browser DevTools console and Node.js REPL | Yes, as a console convenience |
| Web Workers created with `{ type: 'module' }` | Yes |
The runtime parses the whole file before running any of it, so a misplaced await stops the file from loading at all. No part of it runs. In Node.js, the error reads roughly:
SyntaxError: await is only valid in async functions and the top level bodies of modulesNote that "top level" means the module body, not "anywhere in a module". A nested non-async function is still a function:
// utils.mjs
const data = await Promise.resolve([1, 2, 3]); // OK: module top level
function broken() {
// return await Promise.resolve(1); // SyntaxError: not an async function
}
async function fine() {
return await Promise.resolve(1); // OK: inside an async function
}
export { data, fine };Blocks at the top level, such as if, try, for, and bare { }, still count as top level. You can await inside them:
// startup.mjs
import { setTimeout as delay } from 'node:timers/promises';
if (process.env.SLOW_START === '1') {
await delay(500);
}
try {
await delay(10);
console.log('warm-up done');
} catch (err) {
console.error('warm-up failed', err);
}
for await (const tick of [delay(5, 'a'), delay(5, 'b')]) {
console.log(tick); // logs a, then b
}Save that as startup.mjs and run node startup.mjs. It prints warm-up done, then a and b. As the example shows, for await...of also works at the top level.
What Pausing a Module Means
When a module hits a top-level await, three things happen:
- The module's own evaluation suspends at that line. Statements below it have not run yet.
- Every module that imports it, directly or through a chain of imports, waits as well. Their bodies have not started.
- The rest of the program keeps going. Event handlers, timers, and unrelated modules still run. The thread is not blocked the way a synchronous
whileloop would block it.
Point 3 matters. Top-level await is not a "sleep the whole process" switch. It is closer to the module being an async function that the loader awaits before running its dependents.
The next chapter covers how this plays out across sibling modules and deeper import graphs. For now, remember the basic rule: a module that imports another module never runs before that module has finished, awaits included.
Rejections at the Top Level
If a top-level awaited promise rejects and nothing catches it, the module's evaluation fails. The error then spreads:
- Every module that imports the failed module also fails to evaluate.
- A static import graph that includes it fails. In Node.js the process exits with the error. In a browser, the error reaches the console and the module script does not run.
- An
import()of the failed module, or of any module that depends on it, returns a rejected promise. - The failure is cached. Importing the same module again gives the same error. The module is not retried.
// flaky.mjs
await Promise.reject(new Error('database unreachable'));
export const ready = true;
// app.mjs
try {
const mod = await import('./flaky.mjs');
console.log(mod.ready);
} catch (err) {
console.error('flaky.mjs failed:', err.message); // flaky.mjs failed: database unreachable
}
try {
await import('./flaky.mjs');
} catch (err) {
console.error('second attempt:', err.message); // same cached error
}Combining It with import()
Top-level await and import() fit together well. import() returns a promise, and top-level await lets a module wait on that promise while it initializes. Common uses are choosing an implementation at startup and loading optional dependencies:
// storage.mjs
const backend = typeof indexedDB !== 'undefined'
? await import('./storage-indexeddb.mjs')
: await import('./storage-memory.mjs');
export const { get, set } = backend;Modules that import storage.mjs see get and set as ordinary named exports. They don't need to know that one of two implementations was picked at load time. A later chapter on patterns covers this approach and the optional-dependency approach in more detail.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: await is only valid in async functions...` | File is CommonJS or a classic script | Use `.mjs`, `"type": "module"`, or `<script type="module">` |
| Same SyntaxError inside a module | `await` sits in a non-async callback such as `forEach` | Make the callback async, or use a `for...of` loop at the top level |
| Importer reads `undefined` | Still using an async IIFE instead of top-level await | Replace the IIFE with top-level await |
| App starts slowly or shows nothing | A dependency awaits a slow operation | Move the slow work behind `import()` or a function call |
| Module can never be imported again | Top-level rejection was cached | Catch errors inside the module and provide fallbacks |
The forEach case catches many people:
// list.mjs
const urls = ['/a.json', '/b.json'];
// urls.forEach((u) => { await fetch(u); }); // SyntaxError: callback is not async
const results = [];
for (const u of urls) {
results.push(await fetch(u)); // OK: the loop is at the top level
}
export { results };When to Reach for It
Use top-level await when a module cannot do its job until some asynchronous value exists, and every importer would otherwise have to wait for that value anyway. Configuration, a database connection, a WebAssembly instance, and a choice between implementations are good examples.
Avoid it for work that only some code paths need. Each top-level await delays every module that imports this one, and the delay passes up through every import chain to your entry point. If only one feature needs the value, export an async function or use import() at the call site.
Exercise
A file setup.js contains const db = await connect(); and sits in a package whose package.json has no "type" field. Running node setup.js throws a SyntaxError. Give two different ways to fix this without changing the await line.
Show answer
Rename the file to setup.mjs, or add "type": "module" to package.json so Node treats .js files as ES modules. Either way the file loads as a module, and top-level await is valid there.
Exercise
Module a.mjs contains export let value; (async () => { value = await getValue(); })(); and b.mjs does import { value } from './a.mjs'; console.log(value);. What does b.mjs log, and how does top-level await change that?
Show answer
It logs undefined, because a.mjs finishes evaluating as soon as the IIFE starts, before getValue() resolves. If a.mjs uses export const value = await getValue(); instead, b.mjs does not evaluate until the await completes, so it logs the resolved value.
Exercise
A module's top-level await fetch(...) rejects because the network is down. Later, after the network recovers, code calls import() on that module again. What happens, and why?
Show answer
The import() promise rejects with the same original error. A module's evaluation result is cached, failures included, so the loader does not run the module again. To get retry behavior, the module must catch the error itself, for example by retrying in a loop or falling back to a default value.