Course contentsShow
← JavaScript
Lesson 1380 of 2,72330. Async/AwaitFree lesson

Browser vs Node.js Support

Where top-level await is available and how to ensure compatibility across environments.

Browser vs Node.js Support

You'll learn: where top-level await works and how to write code that runs safely in both browsers and Node.js.

Where Top-Level Await Is Available

Top-level await (using await outside an async function) only works in ES modules, but support differs between environments:

Node.js:

  • Supported since Node.js 14.8.0 (stable in v16+)
  • Requires "type": "module" in package.json OR .mjs file extension
  • Works at the top level of module files

Browsers:

  • Supported in modern browsers (Chrome 89+, Firefox 89+, Safari 15+, Edge 89+)
  • Requires <script type="module"> in your HTML
  • Works in module scripts loaded via import or dynamic imports

Think of top-level await like a feature that requires both the right "door" (ES modules) and the right "building" (modern runtime version). Without both, you can't use it.

Ensuring Compatibility

If you need to support older environments, wrap your async initialization in an immediately-invoked async function:

// Top-level await (modern environments only)
const data = await fetch('/api/data').then(r => r.json());

// Compatible fallback (works everywhere)
(async () => {
  const data = await fetch('/api/data').then(r => r.json());
  // Use data here
})();

For libraries or shared code, check the environment capabilities or document that your module requires ES modules with top-level await support. Transpilers like Babel can transform top-level await for older targets, but this changes execution semantics.

Key Takeaway: Top-level await requires ES modules and modern runtimes (Node 14.8+, recent browsers); wrap in an async IIFE for maximum compatibility.