Sub topic 12
Practical Patterns for Top-Level Await
This chapter assumes you know ES module syntax, async/await, and the import() expression. You should also know that top-level await pauses a module's evaluation and holds back every module that imports it. The patterns below use that pause on purpose. Each one finishes asynchronous setup before any importer can read the module's exports.
Pattern 1: Initialize Once, Export Ready Values
Many modules depend on data that arrives asynchronously, such as configuration, a database connection, or a compiled schema. Without top-level await, you would export a promise, or an init() function that every caller must remember to call. With top-level await, the module does the work itself and exports finished values.
// config.js
const response = await fetch('/config.json');
if (!response.ok) {
throw new Error(`Config request failed: ${response.status}`);
}
export const config = await response.json();
// main.js
import { config } from './config.js';
console.log(config.apiUrl); // config is already loaded hereImporters never see a half-initialized module. If the fetch fails, config.js throws, and the error spreads to every module that imports it. A broken configuration stops startup with a clear error and does not fail later in some unrelated place.
Pattern 2: Optional Dependencies
Some packages are useful but not required. You can combine top-level await with import() and try/catch to load such a package if it is installed and turn the feature off if it is not.
// images.js
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 decision happens once, at load time. Every function in the module can then check sharp synchronously.
Pattern 3: Pick an Implementation by Environment
A module can choose between implementations and re-export one stable API. Callers import a single name and do not need to know which environment they run in.
// storage.js
const isNode = typeof process !== 'undefined' && process.versions?.node;
const impl = isNode
? await import('./storage-fs.js')
: await import('./storage-indexeddb.js');
export const { save, load } = impl;Only the chosen file is fetched and evaluated. The other file never loads, which also keeps browser-only code away from Node.js and the other way round.
Choosing a Pattern
| Situation | Pattern | Failure behavior |
|---|---|---|
| Required async setup | Initialize once | Startup fails loudly |
| Nice-to-have package | Optional dependency | Feature disabled, app runs |
| Different runtimes | Pick an implementation | Only the chosen file loads |
Keep the awaited work small and essential in all three patterns. Any time spent inside a top-level await delays every module that imports this one.
Exercise
A module db.js uses top-level await to open a database connection and exports db. A teammate wants the app to keep starting even when the database is down, and to report "offline mode". How would you change db.js, and what should importers check?
Show answer
Wrap the connection in try/catch inside db.js. On success, export the connection. On failure, log the error and export db as null, or export an isOnline flag set to false. Importers check db !== null (or isOnline) before running queries. Because the module catches the error itself, its importers still evaluate, and the app starts in offline mode.