Course contentsShow
← JavaScript
Lesson 1981 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Top-Level Await Patterns

Use top-level await for configuration loading, database connections, or dynamic imports at module initialization.

Top-Level Await Patterns

You'll learn practical patterns for using top-level await to handle initialization tasks cleanly at the module level.

Now that you understand what top-level await is and how it affects module loading, let's explore the most common real-world patterns where it shines.

Configuration Loading

Loading environment-specific config at module initialization becomes elegantly simple:

// config.js
const response = await fetch('/api/config');
export const config = await response.json();

// app.js
import { config } from './config.js';
console.log(config.apiKey); // Ready to use immediately

No wrapper functions, no initialization checks—the config is guaranteed ready when imported.

Database Connections

Establish database connections before any code runs:

// db.js
import { connect } from 'some-db-library';

export const db = await connect(process.env.DATABASE_URL);

// user-service.js
import { db } from './db.js';
// db is already connected and ready
const users = await db.query('SELECT * FROM users');

This ensures your database is ready before any queries run, eliminating race conditions.

Dynamic Imports Based on Environment

Conditionally load modules during initialization:

// feature-flags.js
const flags = await fetch('/api/flags').then(r => r.json());

export const analytics = flags.analytics 
  ? await import('./analytics.js')
  : null;

The right modules load based on runtime conditions, and everything downstream can trust they're ready.

The Pattern

Think of top-level await as your module's "constructor"—it runs once when the module loads, and everything that imports it gets the fully-initialized result. No callbacks, no initialization functions, just clean declarative setup.

Key Takeaway: Use top-level await for configuration loading, database connections, and dynamic imports to eliminate initialization boilerplate and guarantee your modules are ready before any code uses them.