The top-level-await experiment is not enabled

When we try to call an async function with await from a .tsx file in a Next.js React TypeScript web application we get the error message:

Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)

The new versions of Next.js comes with Webpack 5, which supports top level await, but we need to enable it for Next.js too.

  • Open the next.config.js file in the root directory of your Next.js React TypeScript web application
  • Add the following section to it
module.exports = {
  webpack: (config) => {
    config.experiments = { ...config.experiments, topLevelAwait: true };
    return config;
  },
};


Leave a comment

Your email address will not be published. Required fields are marked *