Sub topic 12
Top-Level await in ES Modules
In the earlier chapters, await only worked inside an async function. Top-level await removes that limit for one kind of file, the ES module. In an ES module you can write await directly in the module body, outside any function. This chapter covers where top-level await works, what it does to module loading, and when it helps or hurts your program.
This chapter assumes you already know:
- how
awaitpauses an async function until a Promise settles - how rejected Promises become thrown errors and how
try/catchhandles them - the basics of ES module syntax (
importandexport) - how to run a file with Node.js
Where Top-Level await Works
Top-level await is only allowed in ES modules. An ES module is a JavaScript file that is loaded with module semantics: it can use import and export, it runs in strict mode, and it has its own scope. Other kinds of files do not allow it.
| Environment | How the file becomes an ES module | Top-level await allowed? |
|---|---|---|
| Node.js | File ends in `.mjs`, or `package.json` has `"type": "module"` | Yes (Node 14.8+) |
| Node.js | File ends in `.cjs`, or no `"type": "module"` (CommonJS) | No, `SyntaxError` |
| Browser | Loaded by a script tag with `type="module"` | Yes |
| Browser | Classic script tag without `type="module"` | No, `SyntaxError` |
| Deno, Bun | Modules by default | Yes |
| Browser DevTools console, Node REPL | Console tools special-case it | Yes, as a convenience |
The console row can mislead you. You type await fetch(...) into the DevTools console, it works, and then the same line fails in a plain script file. Consoles add the support themselves. The language only guarantees top-level await inside modules.
The smallest working example is one file:
// hello.mjs — run with: node hello.mjs
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
console.log('waiting...');
const message = await delay(500, 'hello from the top level');
console.log(message);If you rename the file to hello.cjs and run it again, Node reports SyntaxError: await is only valid in async functions and the top level bodies of modules.
What Problem It Solves
Before top-level await, a module that needed async setup had two awkward choices. It could wrap its code in an async immediately invoked function expression (IIFE), or it could export a Promise and make every importer await it.
// Before: an async IIFE. Importers cannot tell when setup is finished.
let config;
(async () => {
const { readFile } = await import('node:fs/promises');
config = JSON.parse(await readFile('./config.json', 'utf8'));
})();
export { config }; // undefined until the IIFE finishesImporters of this module could read config before it was set. Top-level await fixes this: the module does not finish evaluating until its awaits settle. Any module that imports it waits too.
Here is a complete pair of files. First create config.json:
{ "port": 8080, "debug": true }Then config.mjs:
// config.mjs
import { readFile } from 'node:fs/promises';
const text = await readFile(new URL('./config.json', import.meta.url), 'utf8');
export const config = JSON.parse(text);And server.mjs:
// server.mjs — run with: node server.mjs
import { config } from './config.mjs';
// config is guaranteed to be loaded here
console.log(`Starting on port ${config.port}, debug=${config.debug}`);server.mjs never sees an undefined config. The import statement waits until config.mjs has fully evaluated, including its await.
The path is built with new URL('./config.json', import.meta.url), so it resolves relative to the module file and not to the folder you ran node from. This is a common detail in module code that reads files.
How It Works: Async Module Evaluation
Loading ES modules happens in phases. First the loader fetches and parses every module in the import graph and links the imports to the exports. Then it evaluates the modules, dependencies before the modules that import them. Top-level await only changes the evaluation phase.
When a module contains a top-level await, its evaluation becomes asynchronous, much like the body of an async function. The rules are:
- A module that uses top-level await starts running, then suspends at the first
await. - Any module that imports it, directly or through other modules, does not start evaluating until it finishes.
- Modules that do not depend on it can keep evaluating while it is suspended.
Three files show the order:
// a.mjs
console.log('a: start');
await new Promise(resolve => setTimeout(resolve, 500));
console.log('a: end');
export const a = 'A';// b.mjs
console.log('b: run');
export const b = 'B';// main.mjs — run with: node main.mjs
import { a } from './a.mjs';
import { b } from './b.mjs';
console.log('main:', a, b);Output:
a: start
b: run
a: end
main: A Bb.mjs ran while a.mjs was suspended, because b.mjs does not import a.mjs. main.mjs imports both, so its body waited for both. Import order still decides which module starts first. Top-level await never lets a module run before its own dependencies.
Dynamic import() waits too
import() returns a Promise. When the target module (or anything it depends on) uses top-level await, that Promise fulfills only after evaluation finishes:
// loader.mjs — run with: node loader.mjs (a.mjs from above in the same folder)
console.log('before import');
const mod = await import('./a.mjs');
console.log('loaded:', mod.a);The output is before import, a: start, a: end, loaded: A.
Common Uses
These are the situations where top-level await is a good fit:
- Loading configuration or data at startup, as in
config.mjsabove. - Conditional or fallback imports, where you pick a module at runtime:
// json-parser.mjs
let parse;
try {
// A package that may not be installed
({ parse } = await import('fast-json-parse-lib'));
} catch {
parse = JSON.parse;
}
export { parse };- Opening a shared resource once, such as a database connection that every importer reuses. The connection is ready before any importer runs.
- Short scripts and tools, where wrapping everything in
async function main()adds noise.
Gotchas and Failure Modes
Blocking the whole import graph
A slow top-level await delays every module that depends on it. If a module near the root of your app awaits a 3-second network call, nothing that imports it can start for 3 seconds. That includes your server, your UI, and your tests. Libraries are the worst place for this, because one slow await inside a package delays every application that imports it.
A rejection makes the module fail
If a top-level await rejects and nothing catches it, the module ends up in an error state. Every static importer fails to load, and every import() of it rejects with the same error. Module records are cached, so importing it again does not retry. You get the cached failure back.
// broken.mjs
await Promise.reject(new Error('setup failed'));
export const value = 1;// try-broken.mjs — run with: node try-broken.mjs
for (let i = 1; i <= 2; i++) {
try {
await import('./broken.mjs');
} catch (err) {
console.log(`attempt ${i}:`, err.message);
}
}
// attempt 1: setup failed
// attempt 2: setup failedIf the failure can be recovered from, catch it inside the module with try/catch and export a fallback value or an explicit error state.
Deadlocks with dynamic imports in cycles
Static import cycles still work with top-level await, because the loader evaluates the cycle as a group. A module can still deadlock itself, though, by awaiting import() of a module that statically imports it back:
// cycle-a.mjs — run with: node cycle-a.mjs
console.log('cycle-a: start');
await import('./cycle-b.mjs'); // cycle-b needs cycle-a to finish first
console.log('cycle-a: never reached');
export const x = 1;// cycle-b.mjs
import { x } from './cycle-a.mjs';
console.log('cycle-b:', x);cycle-a waits for cycle-b, and cycle-b waits for cycle-a to finish evaluating. Neither can move forward. When nothing else is left on the event loop, Node prints Warning: Detected unsettled top-level await and exits with code 13. Exit code 13 is a useful clue when a process quits for no clear reason.
Mixing with CommonJS
CommonJS code cannot synchronously require() a module that uses top-level await. require() has to return right away, and the module cannot finish right away. Newer Node versions can require() synchronous ES modules, but they throw ERR_REQUIRE_ASYNC_MODULE for a module with top-level await. From CommonJS, use import() inside an async function:
// use-config.cjs — run with: node use-config.cjs
async function main() {
const { config } = await import('./config.mjs');
console.log('port from CommonJS:', config.port);
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});Sequential awaits at the top level
The sequential-versus-parallel rule from earlier chapters still applies. Two independent awaits at the top level add their durations together. Start the operations together and use Promise.all:
// parallel-top.mjs
import { readFile } from 'node:fs/promises';
const [pkg, readme] = await Promise.all([
readFile(new URL('./package.json', import.meta.url), 'utf8'),
readFile(new URL('./README.md', import.meta.url), 'utf8')
]);
console.log(pkg.length, readme.length);Choosing an Approach
| Approach | Importers wait automatically? | Who controls timing | Best for |
|---|---|---|---|
| Top-level await | Yes | The module | App-level setup, scripts, fallback imports |
| Export an async `init()` function | No, caller awaits it | The caller | Libraries, slow or optional setup |
| Export a Promise | No, every use must await it | Shared | Lazy values used in only a few places |
| Async IIFE | No, and importers cannot tell when it finished | Nobody | Legacy code (avoid in new modules) |
A quick rule: use top-level await when every importer needs the value before it can do anything useful, and the wait is short. In every other case, export a function and let the caller decide when to wait.
Exercise
You have three modules. logger.mjs has no imports and no await. db.mjs uses top-level await to open a connection that takes 2 seconds. app.mjs imports logger.mjs first and then db.mjs, and logs "app ready" in its body. Each of logger.mjs and db.mjs logs a line as its first statement. In what order do the lines appear, and about how long until "app ready" prints?
Show answer
logger.mjs's line prints first, then db.mjs's first line, then (after about 2 seconds) any lines db.mjs logs after its await, and finally "app ready". app.mjs depends on db.mjs, so its body cannot run until db.mjs finishes evaluating. "app ready" prints after about 2 seconds.
Exercise
A teammate's script works in the Node REPL but fails with "SyntaxError: await is only valid in async functions and the top level bodies of modules" when run as tool.js. List two fixes that keep the top-level await.
Show answer
Rename the file to tool.mjs, or add "type": "module" to the nearest package.json so .js files load as ES modules. The REPL accepted the code because it supports top-level await as a convenience, but a CommonJS file does not.
Exercise
A module does export const settings = await fetchRemoteSettings(); and the remote server is sometimes down. Every importer then crashes, and later attempts to import the module in the same process fail with the same error. Why does retrying not help, and how would you restructure the module?
Show answer
A module whose evaluation rejects is cached in an error state, so later imports return the same error and the module is never evaluated again. Wrap the await in try/catch inside the module and export a fallback (for example default settings plus an error flag). The alternative is to export an async function such as loadSettings() that callers can call and retry themselves.