Sub topic 12
Top-Level await in ES Modules
This chapter assumes you already know how await pauses an async function, how a rejected Promise throws at the await expression, and how to run a file with Node.js. You also need a basic idea of import and export.
Before top-level await, you could use await only inside an async function. To load data when a module started up, you had to wrap the code in an async function and call it right away. Top-level await removes that wrapper. You can write await directly at the top level of an ES module, outside any function.
Where It Works
Top-level await is allowed only in ES modules. In a classic browser script or a CommonJS file, it is a SyntaxError.
| Environment | How the file becomes an ES module | Top-level await? |
|---|---|---|
| Node.js | `.mjs` extension, or `"type": "module"` in `package.json` | Yes (Node 14.8+) |
| Browser | `<script type="module">` | Yes, in modern browsers |
| Node.js CommonJS | `.cjs`, or no `"type": "module"` | No |
| Browser classic script | `<script>` without `type="module"` | No |
A Worked Example
Create two files in the same folder.
// config.mjs
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
console.log('config: loading');
export const config = await delay(500, { port: 3000, debug: true });
console.log('config: ready');// main.mjs
import { config } from './config.mjs';
console.log('main: starting on port', config.port);Run node main.mjs. The output is:
config: loading
config: ready
main: starting on port 3000The body of main.mjs does not run until config.mjs has finished evaluating, and that includes its awaited Promise. So config is always fully set when main.mjs reads it. You never see a half-loaded value.
While config.mjs is paused, the event loop keeps running. Timers fire and other modules that do not depend on config.mjs can still evaluate. Only the modules that import it, directly or through other imports, have to wait.
Good Uses
- Loading configuration or secrets once before anything else uses them.
- Choosing a module at runtime with dynamic
import(), for exampleconst { parse } = await import(useFast ? './fast.mjs' : './safe.mjs');. - Opening a database connection or fetching initial data that every importer needs.
- Short scripts and command-line tools, where a wrapper function adds nothing.
Common Errors
Using it in the wrong file type. If you write await at the top of a .js file without "type": "module", Node.js reports a syntax error such as "await is only valid in async functions and the top level bodies of modules". Rename the file to .mjs or set the module type.
Slow startup for every importer. A long await in a widely imported module delays every module that imports it. Libraries should usually export an async function, such as export async function connect(), and let the caller decide when to wait.
Unhandled rejection breaks the import. If the awaited Promise rejects and nothing catches it, the module fails to load and so does every module that imports it. Use try/catch at the top level when a fallback makes sense:
// settings.mjs
let settings;
try {
const response = await fetch('https://api.example.com/settings');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
settings = await response.json();
} catch (err) {
console.warn('Using default settings:', err.message);
settings = { theme: 'light' };
}
export { settings };Circular imports. If two modules import each other and one of them awaits at the top level, evaluation can stall or expose uninitialized bindings. Avoid top-level await inside import cycles.
Loading from CommonJS. require() cannot load an ES module that uses top-level await, because require() is synchronous. Newer Node.js versions throw ERR_REQUIRE_ASYNC_MODULE. Use await import() instead.
Exercise
A file named app.js contains const data = await fetch('https://example.com'); at the top level. The project's package.json has no "type" field. What happens when you run node app.js, and what are two ways to fix it?
Show answer
Node.js treats app.js as CommonJS, so the top-level await causes a SyntaxError. To fix it, rename the file to app.mjs, or add "type": "module" to package.json. Wrapping the code in an async function and calling it would also work.
Exercise
Module a.mjs imports b.mjs, and b.mjs runs await delay(2000) at its top level. Module c.mjs imports neither of them. If an entry file imports all three, which modules have to wait for the 2-second delay?
Show answer
Only a.mjs has to wait, because it depends on b.mjs. The entry file's own body also waits, because it imports both. c.mjs has no dependency on b.mjs, so it can evaluate without waiting for the delay.