fetch()
The global WHATWG Fetch API for making HTTP requests.
Syntax
await fetch(input[, init]) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
input | string | URL | Request | Yes | The resource to fetch. |
init | object | No | Options: `method`, `headers`, `body`, `signal`, `redirect`. |
Returns
Promise<Response> — Resolves with a Response object.
Examples
const res = await fetch('https://api.example.com/users/1');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
console.log(user.name);
Output
Ada Lovelace
const res = await fetch('https://api.example.com/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'widget' }),
signal: AbortSignal.timeout(5000),
});
console.log(res.status);
Output
201
Notes
Stable since Node 21 (experimental from 18). It does NOT reject on
HTTP error status - check `res.ok`/`res.status` yourself. Use
`AbortSignal.timeout()` to avoid hanging requests. The body can be
read only once.