How to Fetch API in JavaScript
Short answer: call fetch(url), which returns a Promise for a Response. Check response.ok, then read the body with await response.json(). It works in all modern browsers and in Node.js 18 and later.
A basic GET request
async function getPosts() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
console.log(data);
}
getPosts().catch(console.error);
The function uses async/await, which makes Promise code read like normal steps. If that is new, read promises and async/await.
Sending data with POST
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello', body: 'World', userId: 1 }),
});
const created = await res.json();
You must convert objects with JSON.stringify and set the Content-Type header, otherwise the server will not parse the body as JSON.
The options object
| Option | What it does |
|---|---|
method | GET (default), POST, PUT, PATCH, DELETE |
headers | Extra headers such as Authorization |
body | The data you send (string, FormData, Blob) |
credentials | Whether to send cookies (include, same-origin) |
signal | Lets you cancel the request |
cache | Controls browser caching behavior |
Error handling: the part most people miss
fetch only rejects its Promise on network failures such as no connection. A 404 or 500 response does not throw. Always check the status yourself:
try {
const res = await fetch('/api/users');
if (!res.ok) {
throw new Error('Request failed with status ' + res.status);
}
const users = await res.json();
} catch (err) {
console.error('Could not load users:', err.message);
}
For the meaning of each code, see HTTP status codes.
Add a timeout and cancel requests
const res = await fetch('/api/slow', { signal: AbortSignal.timeout(5000) });
For manual cancellation, such as when a user leaves a page, create an AbortController, pass controller.signal to fetch, and call controller.abort(). The Promise then rejects with an AbortError.
Run requests in parallel
const [users, posts] = await Promise.all([
fetch('/api/users').then((r) => r.json()),
fetch('/api/posts').then((r) => r.json()),
]);
Independent requests should run together instead of one after another.
Sending form files
const form = new FormData();
form.append('avatar', fileInput.files[0]);
await fetch('/upload', { method: 'POST', body: form });
Do not set Content-Type yourself here. The browser adds the correct multipart boundary.
Common mistakes
- Forgetting
awaitbeforeres.json(), which returns a Promise instead of data. - Reading the body twice. A response body can be consumed only once; use
res.clone()if you need two reads. - Ignoring CORS. If the server does not allow your origin, the browser blocks the response.
- Not handling loading and error states in the user interface.
Fetch vs Axios
Axios parses JSON automatically and rejects on bad status codes, but fetch is built in and needs no dependency. For most apps, a small wrapper around fetch is enough.
Frequently asked questions
Why does fetch not throw an error on a 404 response?
fetch only rejects on network failures. An HTTP error such as 404 or 500 still resolves, so you must check response.ok or response.status yourself and throw if needed.
Should I use fetch or Axios?
fetch is built into browsers and Node.js 18 and later, so it needs no dependency. Axios adds conveniences such as interceptors and automatic JSON handling. Use fetch for simple needs and Axios if you want those extras.
Next steps
Learn what you are calling in what an API is, and build your own with Node.js and Express.
