Fetch API
fetch() is the modern way for JavaScript to make HTTP requests: load JSON from an API, submit a form in the background, download a file. It returns a promise, so it works naturally with async/await.
How real requests look
In your own projects, you'll usually call an API on your server or a public service:
// GET JSON from an API
const response = await fetch("https://api.example.com/users/42");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
console.log(user.name);
// POST JSON to an API
const res = await fetch("/api/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Learn fetch", done: false }),
});
const created = await res.json();Note: The playgrounds on this site run in sandboxed frames with no origin of their own, so they can't reach this site's server, and many public APIs don't allow requests from such frames. The examples below therefore fetch
data:URLs and Blob URLs — the data travels through exactly the samefetch→Response→.json()steps as a real network response.
Fetch in two steps
Using fetch always has two steps:
await fetch(url)resolves to a Response as soon as the headers arrive.await response.json()(or.text(),.blob()…) reads and parses the body.
const payload = { id: 42, name: "Ada", skills: ["math", "code"] };
const url = "data:application/json," + encodeURIComponent(JSON.stringify(payload));
const response = await fetch(url);
console.log("ok:", response.ok, "status:", response.status);
console.log("type:", response.headers.get("content-type"));
const user = await response.json();
console.log(user.name, user.skills);ok: true status: 200
type: application/json
Ada [ 'math', 'code' ]
The Response object
| Member | Meaning |
|---|---|
response.ok |
true for status 200–299 |
response.status / statusText |
e.g. 404 / "Not Found" |
response.headers.get(name) |
read a response header |
response.json() |
parse the body as JSON (promise) |
response.text() |
body as a string (promise) |
response.blob() / arrayBuffer() |
binary data (promise) |
A body can be read only once — call either json() or text(), not both (or use response.clone()).
Error handling
fetch only rejects on network failures (offline, DNS error, blocked request). An HTTP error like 404 or 500 still resolves — you must check response.ok yourself. A robust helper handles both cases, plus invalid JSON:
async function getJson(url) {
let response;
try {
response = await fetch(url);
} catch (err) {
throw new Error("Network error: " + err.name);
}
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
try {
return await response.json();
} catch {
throw new Error("Response was not valid JSON");
}
}
const good = "data:application/json," + encodeURIComponent('{"items":[1,2,3]}');
const broken = "data:application/json," + encodeURIComponent("{not json");
for (const url of [good, broken, "nope://invalid"]) {
try {
const data = await getJson(url);
console.log("data:", data);
} catch (err) {
console.log("failed:", err.message);
}
}data: { items: [ 1, 2, 3 ] }
failed: Response was not valid JSON
failed: Network error: TypeError
Fetching a Blob URL
URL.createObjectURL(blob) gives in-memory data its own temporary URL. Here we create a "file" in the browser, fetch it, and render the result — the same code would work with a real API URL:
<style>
table { border-collapse: collapse; margin-top: 8px; }
td, th { border: 1px solid #ccc; padding: 4px 10px; }
</style>
<button id="load">Load products</button>
<div id="out"></div>
<script type="module">
const products = [
{ name: "Notebook", price: 3.5, stock: 120 },
{ name: "Pen", price: 1.2, stock: 0 },
{ name: "Backpack", price: 39, stock: 8 },
];
// Pretend this is a JSON file on a server:
const blob = new Blob([JSON.stringify(products)], { type: "application/json" });
const url = URL.createObjectURL(blob);
document.getElementById("load").addEventListener("click", async () => {
const out = document.getElementById("out");
out.textContent = "Loading…";
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const items = await res.json();
const table = document.createElement("table");
table.innerHTML = "<tr><th>Product</th><th>Price</th><th>Status</th></tr>";
for (const p of items) {
const row = table.insertRow();
row.insertCell().textContent = p.name;
row.insertCell().textContent = p.price.toFixed(2) + " €";
row.insertCell().textContent = p.stock > 0 ? `${p.stock} in stock` : "sold out";
}
out.replaceChildren(table);
console.log("loaded", items.length, "products from", url.slice(0, 10) + "…");
} catch (err) {
out.textContent = "Could not load products: " + err.message;
}
});
</script>Request options
The second argument to fetch configures the request:
| Option | Example | Purpose |
|---|---|---|
method |
"POST", "PUT", "DELETE" |
HTTP method (default GET) |
headers |
{ "Content-Type": "application/json" } |
request headers |
body |
JSON.stringify(data), new FormData(form) |
data to send |
signal |
controller.signal |
cancel with an AbortController |
credentials |
"include" |
send cookies to another origin |
Cancelling a slow request — or giving up after a timeout — uses an abort signal:
const res = await fetch("/api/report", { signal: AbortSignal.timeout(5000) });
// rejects with a "TimeoutError" if it takes longer than 5 secondsSeveral requests at once
Independent requests should run in parallel:
const toUrl = (obj) => "data:application/json," + encodeURIComponent(JSON.stringify(obj));
const urls = [toUrl({ city: "Oslo", temp: 4 }), toUrl({ city: "Rome", temp: 17 }), toUrl({ city: "Cairo", temp: 26 })];
const results = await Promise.all(urls.map((u) => fetch(u).then((r) => r.json())));
for (const { city, temp } of results) {
console.log(`${city.padEnd(6)} ${String(temp).padStart(3)} °C`);
}Oslo 4 °C
Rome 17 °C
Cairo 26 °C
Tip: Requests to a different origin are subject to CORS: the server must send an
Access-Control-Allow-Originheader allowing your site, or the browser blocks the response. That's a server setting — you can't fix it from client-side JavaScript.
Test yourself
Does fetch reject its promise for an HTTP 404 response?
- Yes, always
- No — it resolves; check response.ok
- Only for POST requests
- Only if the body is empty
How do you read a JSON body from a Response?
- response.body
- JSON.parse(response)
- await response.json()
- response.data
Which header tells the server you're sending JSON?
- Accept: text/html
- Content-Type: application/json
- Authorization: JSON
- X-JSON: true