Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 413
Yilmaz Avatar asked Dec 03 '25 03:12

Yilmaz


1 Answers

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) => {
    // this will override the experiments
    config.experiments = { ...config.experiments, topLevelAwait: true };
    // this will just update topLevelAwait property of config.experiments
    // 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>
  );
}

Next 13

same setting works at "next": "^13.1.6", in both "pages" and "app" directory. (Because this feature is a webpack5 feature, not next.js feature) you can test it with this sample code:

const _promise = async () => {
  return new Promise((resolve, reject) => resolve(4));
};
// you might get typecsript warning
const val = await _promise();
console.log("val", val);

Warning

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

like image 85
Yilmaz Avatar answered Dec 04 '25 16:12

Yilmaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!