'await' is only allowed in async functions
Error message
'await' is only allowed within async functions
Quick summary
You used the `await` keyword outside of an async function or at the top level without top-level await support. await requires an async context.
Why this happens
Using await in a non-async function
Using await at the top level without ESM module support
Forgetting to add
asyncto a function that uses awaitUsing await in a callback that isn't async
Minimal example
function fetchData() {
const data = await fetch("/api"); // not in async function
}async function fetchData() {
const data = await fetch("/api");
}Add the async keyword to the function declaration.
How to diagnose
Check if the enclosing function is declared with
asyncCheck if you're at the top level (needs ESM + top-level await)
Look for callbacks that need to be async
How to fix
Add
asyncto the enclosing function:async function foo()Use
.then()instead of await for non-async callbacksEnable top-level await in tsconfig (module: ESNext, target: ES2022)
Wrap the code in an async IIFE:
(async () => { await ... })()
How to prevent
Always add
asyncwhen usingawaitin a functionUse ESLint with require-await rule