Sub topic 12
Practical Patterns for Top-Level Await
This chapter assumes you already know ES module import/export syntax, promises and async/await, and the import() expression. It also assumes you have seen how top-level await pauses a module and the modules that import it. The examples run in Node.js 18 or later with .mjs files or "type": "module" in package.json, unless a browser is stated.
Top-level await fits one job: a module must finish some asynchronous work before its exports are usable. The patterns below share one rule. Do the async work once, at the edge of the module graph, and export values that are already resolved.
Pattern 1: Resolve Configuration Once
The most common use is to load configuration at startup and export the result. Each importer receives a plain object, not a promise.
// config.js
const response = await fetch('/config.json');
if (!response.ok) {
throw new Error(`Config request failed with status ${response.status}`);
}
export const config = await response.json();
// main.js
import { config } from './config.js';
console.log(config.apiUrl); // runs only after config.js has finished evaluatingThe status check matters. fetch resolves on HTTP errors such as 404, so a missing file would otherwise cause a confusing JSON parse error. When config.js throws, every module that depends on it fails to evaluate, which is usually what you want for required configuration.
In Node.js, the same pattern reads a local file:
// config.mjs
import { readFile } from 'node:fs/promises';
const raw = await readFile(new URL('./config.json', import.meta.url), 'utf8');
export const config = Object.freeze(JSON.parse(raw));new URL(..., import.meta.url) resolves the path relative to the module file instead of the current working directory. Object.freeze stops importers from changing a value that every other importer shares.
Pattern 2: Initialize a Resource Before Exporting It
Some resources need asynchronous setup before they can be used at all. Examples include WebAssembly instances, database pools, and caches that warm up at startup. Top-level await lets the module export the ready resource directly.
// math-wasm.mjs
// A minimal WebAssembly module exporting add(a, b) for 32-bit integers.
const bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic + version
0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // type: (i32, i32) -> i32
0x03, 0x02, 0x01, 0x00, // function section
0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // export "add"
0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, // body
]);
const { instance } = await WebAssembly.instantiate(bytes);
export const add = instance.exports.add;
// app.mjs
import { add } from './math-wasm.mjs';
console.log(add(2, 3)); // 5Without top-level await, math-wasm.mjs would have to export an init() function or a promise, and every caller would have to remember to await it. With top-level await, nobody can call add before it exists.
Pattern 3: Optional Dependencies with a Fallback
Combining top-level await with import() and try/catch lets a module check once, at startup, whether a package is installed.
// images.mjs
let sharp = null;
try {
sharp = (await import('sharp')).default;
} catch {
console.warn('Optional dependency "sharp" is not installed; image resizing disabled');
}
export function canResize() {
return sharp !== null;
}
export async function resize(input, width) {
if (!sharp) throw new Error('Image resizing is unavailable');
return sharp(input).resize(width).toBuffer();
}The rest of the application calls canResize() synchronously. The cost of the check is paid once, during module evaluation.
Pattern 4: Choose an Implementation at Startup
When the right implementation depends on the environment, pick it once and re-export a stable interface.
// storage.js (browser)
const impl = typeof indexedDB !== 'undefined'
? await import('./idb-store.js')
: await import('./memory-store.js');
export const getItem = impl.getItem;
export const setItem = impl.setItem;Importers write import { getItem } from './storage.js' and never see the branch. Bundlers still create separate chunks for both files, because each import() has a literal specifier. Only the chosen chunk is downloaded.
Pattern 5: Start Independent Work in Parallel
Two await statements in a row run one after the other. When the tasks do not depend on each other, start them together:
// bootstrap.mjs
import { readFile } from 'node:fs/promises';
const [schemaText, { default: Ajv }] = await Promise.all([
readFile(new URL('./schema.json', import.meta.url), 'utf8'),
import('ajv'),
]);
const ajv = new Ajv();
export const validate = ajv.compile(JSON.parse(schemaText));The total wait is set by the slowest task instead of the sum of all of them. This matters more at the top level than inside a function, because every importer waits for it.
Pattern 6: Put a Deadline on Startup Work
A network call that never settles would block every dependent module forever. Wrap remote work in a timeout so failure is loud and fast:
// remote-flags.js
function withTimeout(promise, ms, label) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
let flags = { newCheckout: false };
try {
const res = await withTimeout(fetch('/flags.json'), 2000, 'Feature flags');
if (res.ok) flags = await res.json();
} catch (err) {
console.warn('Using default feature flags', err);
}
export { flags };For flags, a default is safe, so the module recovers. For required configuration (Pattern 1), let the timeout error propagate.
fetch also accepts signal: AbortSignal.timeout(2000) in modern browsers and Node.js 18 and later, which cancels the request itself. The Promise.race helper above works with any promise.
Pattern 7: Keep Awaiting Modules Small and at the Leaves
Top-level await delays the module that uses it and every module that imports it, directly or indirectly. Keep the waiting in small, dedicated modules such as config.js, storage.js, and math-wasm.mjs. Import them only where they are needed. Avoid putting top-level await in a shared utility or barrel file (an index.js that re-exports many modules), because then the whole application waits on it.
The next chapter covers what goes wrong when this rule is broken, including cycles and deadlocks.
Choosing Between Top-Level Await and the Alternatives
Top-level await is one of three ways to expose asynchronously prepared data.
| Approach | What importers receive | Best when | Drawback |
|---|---|---|---|
| Top-level await | The ready value | Every importer needs the value before doing anything | Delays all dependents; failure blocks the graph |
| Export a promise | A promise to await | Some code paths never need the value | Every caller must remember to await |
| Export a lazy async function | A function that loads on first call | The work is expensive and often unused | First call is slow; caching is your job |
A lazy function with caching looks like this:
// lazy-config.js
let cached;
export function getConfig() {
cached ??= fetch('/config.json').then((r) => r.json());
return cached;
}Use top-level await when "not ready yet" should never be a state your code has to handle. Use the other two when startup speed matters more than convenience, or when the value is optional on most paths.
Exercises
Exercise
A module contains const users = await fetch('/users.json').then(r => r.json()); const roles = await fetch('/roles.json').then(r => r.json()); export { users, roles };. Each request takes about 300 ms. How long do importers wait, and how would you rewrite it?
Show answer
About 600 ms, because the second fetch starts only after the first finishes. Start both together: const [users, roles] = await Promise.all([fetch('/users.json').then(r => r.json()), fetch('/roles.json').then(r => r.json())]);. The wait drops to about 300 ms.
Exercise
A logging helper used by 40 modules gains const transport = await import('./remote-transport.js'); at its top level. Startup slows down noticeably. Why, and which alternative from the decision table fits better?
Show answer
Every module that imports the logger, directly or indirectly, now waits for remote-transport.js to load before it evaluates, so the delay spreads across most of the app. A lazy async function (or an exported promise) fits better: load the transport on the first log call and buffer messages until it is ready, so importers are not blocked.
Exercise
In Pattern 3, why might catch {} hide a real bug, and how do you narrow it?
Show answer
It catches every error, including errors thrown while an installed but broken package evaluates. Catch the error as err, treat only err.code === 'ERR_MODULE_NOT_FOUND' as "not installed", and rethrow anything else.