how can I use top level "await" in typescript next.js

When I use "await" on top-level like this:

 const LuckyDrawInstance=await new web3.eth.Contract(abi)

I got a warning on the terminal: "set experiments.topLevelAwait true". When I tried to add this to "tsconfig.json", it still does not work. it says "experiments" property does not exist.

I could wrap it inside an async function but I want to set it without a wrapped function.


Solution 1:

It is nothing to do with the tsconfig.json. You have to set it inside next.config.js. New version of next.js uses webpack5 and webpack5 supports top level await.

module.exports = {
  webpack: (config) => {
    config.experiments = { topLevelAwait: true };
    return config;
  },
};

NOTE

You have to use it outside the functional component:

export default function Navbar() {
  // this will throw error
  // Syntax error: Unexpected reserved word 'await'.
  const provider=await customFunction()

  return (
    <section>          
    </section>
  );
}

Warning

Since it is experimental, it might be broken in some versions