How to use top-level await in JavaScript modules
· Category: JavaScript
Short answer
Top-level await lets you use await outside of async functions at the module level, blocking module execution until the Promise settles and simplifying initialization code.
Steps
- Use in an ES module (type="module"):
javascript // config.js const res = await fetch("/api/config"); export const config = await res.json(); - Import the awaited value elsewhere:
javascript import { config } from "./config.js"; console.log(config.apiUrl); - Wrap initialization in try/catch at the top level:
javascript let db; try { db = await connectDatabase(); } catch (err) { console.error("Database connection failed"); } export { db };
Tips
- Top-level await is supported in modern browsers, Node.js 14.8+, and Deno.
- It pauses module evaluation, which can affect startup time if overused.
Common issues
- Using top-level await in non-module scripts throws a syntax error.
- Circular dependencies with top-level await can deadlock module loading.