Top-Level Await Pitfalls
You'll learn: How top-level await can unintentionally slow down or break your application if not used carefully.
The Problem with Blocking
While top-level await is powerful, it comes with a serious cost: it blocks the entire module graph. When a module uses top-level await, every module that depends on it must wait for that promise to resolve before initialization continues. This creates a cascading delay that can significantly slow your application's startup time.
Think of it like a traffic light at a major intersection. When one light turns red (a module awaits), all traffic behind it (dependent modules) must wait—even if they don't actually need what that module is doing. The more modules that depend on the awaiting module, the bigger the traffic jam.
Use Sparingly
Top-level await should be reserved for truly essential initialization that must complete before the module can be used:
// ❌ Bad: Blocking for non-critical data
const userData = await fetch('/api/user').then(r => r.json());
// ✅ Better: Defer non-critical loading
const userDataPromise = fetch('/api/user').then(r => r.json());
Always Handle Errors
An unhandled rejection in top-level await will prevent your entire module from loading, potentially breaking your whole application:
// ❌ Bad: Unhandled failure breaks everything
const config = await fetch('/config.json').then(r => r.json());
// ✅ Better: Handle failures gracefully
const config = await fetch('/config.json')
.then(r => r.json())
.catch(() => ({ /* fallback defaults */ }));
Key Takeaway: Top-level await blocks all dependent modules, creating potential bottlenecks and failure points. Use it only when absolutely necessary, always handle errors with catch blocks, and consider whether lazy loading or deferred initialization would be more appropriate.