The Fetch API
Overview
fetch requests a URL and gives you back a promise for the response. It’s how web pages talk to servers: loading data, saving changes, searching, uploading files.
const response = await fetch('/api/courses');
const courses = await response.json();Reading the body is a second step: response.json(), response.text() and response.blob() all return promises too. That’s because the response headers arrive first, and the body may still be downloading.
Requests and responses
Every HTTP exchange has two halves.
The request says what you want:
- a URL —
/api/courses/42 - a method —
GETto read,POSTto create,PUT/PATCHto update,DELETEto remove - headers — extra information, such as the type of data being sent
- an optional body — the data you’re sending
The response says what happened:
- a status code —
200OK,201Created,404Not Found,500Server Error - headers — such as
Content-Type: application/json - a body — the data itself
const res = await fetch('/api/courses');
res.status; // 200
res.ok; // true for any status 200–299
res.headers.get('Content-Type'); // 'application/json; charset=utf-8'Checking for errors
A 404 or 500 response is still a successful fetch — the server answered. Check ok yourself:
const response = await fetch('/api/courses/42');
if (!response.ok) {
throw new Error(`Server replied ${response.status}`);
}fetch itself only rejects when the request couldn’t be made at all, for example when the user is offline.
A full, careful request handles both kinds of failure:
async function getJson(url) {
let res;
try {
res = await fetch(url);
} catch (error) {
throw new Error('Network problem — are you online?', { cause: error });
}
if (!res.ok) {
throw new Error(`Server error ${res.status} for ${url}`);
}
return res.json();
}Wrap it once like this and reuse it everywhere, instead of repeating the checks.
Query strings
To send parameters in a GET request, build the URL with URLSearchParams, which encodes spaces and special characters correctly:
const params = new URLSearchParams({ q: 'arrow functions', level: 'Beginner' });
const res = await fetch(`/api/search?${params}`);
// /api/search?q=arrow+functions&level=BeginnerGluing user input straight into a URL ('/api/search?q=' + input) breaks as soon as someone types & or #.
Sending data
await fetch('/api/progress', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ topic: 'fetch-api', done: true }),
});The Content-Type header tells the server the body is JSON. Forgetting JSON.stringify is a common mistake — the body would be sent as the useless text [object Object].
Sending form data and files
For HTML forms and file uploads, pass a FormData object as the body. The browser sets the right headers for you:
const form = document.querySelector('#profile');
await fetch('/api/profile', {
method: 'POST',
body: new FormData(form), // includes any <input type="file"> too
});Authentication headers
APIs often need a token in a header:
await fetch('/api/me', {
headers: { Authorization: `Bearer ${token}` },
});Never put secret API keys in browser JavaScript — anyone can read them. Secrets belong on your server.
Cancelling a request
const controller = new AbortController();
fetch('/api/search?q=loops', { signal: controller.signal });
controller.abort(); // e.g. when the user types againAn aborted fetch rejects with an AbortError, which you usually ignore. You can also give a request a time limit:
const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); // give up after 5 sShowing loading and error states
Real interfaces show the user what’s happening:
async function showCourses() {
list.textContent = 'Loading…';
try {
const courses = await getJson('/api/courses');
list.innerHTML = courses.map((c) => `<li>${c.title}</li>`).join('');
} catch (error) {
list.textContent = 'Could not load courses. Please try again.';
console.error(error);
}
}(In real code, prefer creating elements over innerHTML for data from a server — see Creating elements.)
CORS
CORS errors mean the server didn’t allow requests from your page’s origin. That has to be fixed on the server, not in your fetch call.
Browsers only let a page read responses from its own origin (same protocol, domain and port) unless the other server says otherwise with Access-Control-Allow-… headers. This protects users: a random website can’t quietly read your bank’s API using your logged-in session. If you control the API, add the right headers there; if you don’t, call it from your own server instead.
You can debug any of these issues in the Network panel of DevTools, which shows every request, its status, headers and body.
Load a list of courses
Write loadCourses() that fetches /api/courses, throws if the response isn’t OK, and returns the parsed JSON. Then write saveProgress(topic) that POSTs { topic, done: true } as JSON to /api/progress.
async function loadCourses() {
// your code here
}
async function saveProgress(topic) {
// your code here
}async function loadCourses() {
const res = await fetch('/api/courses');
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return res.json();
}
async function saveProgress(topic) {
const res = await fetch('/api/progress', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ topic, done: true }),
});
if (!res.ok) throw new Error(`Save failed: ${res.status}`);
}Summary
fetchreturns a promise for aResponse; reading the body is a second promise.- It only rejects on network failure — check
response.okfor HTTP errors. - Send JSON with
method,headersand a stringifiedbody. - Build query strings with
URLSearchParamsso values are encoded safely. - Cancel requests with
AbortController; CORS errors must be fixed on the server.