In short
Your page needs data from a server: courses, results, cricket scores. fetch is the built-in way to ask for it without reloading the page.
fetch is the browser's built-in way to make HTTP requests from JavaScript. It returns a promise, and you call response.json() to read JSON data.

Think of it like this
Ordering on Swiggy
You place the order and carry on with life. The app says 'on the way', and later the food arrives, or you get a 'restaurant closed' message. fetch works the same: send the request, keep the page running, handle whatever comes back.
Watch it happen
A safe fetch, step by step
GET /api/courses
1/5fetch sends the request. The page keeps running while it waits, nothing freezes.
The big ideas
What you need to know
It returns a Promise
fetch doesn't block the page. Use await to wait for the response without freezing anything.
Two steps to the data
First you get a Response. Then you read its body with res.json() or res.text(), which is also async.
404 isn't an error to fetch
fetch only rejects on network failure. For 404 or 500 it resolves, so always check res.ok.
Add a timeout
AbortSignal.timeout(5000) cancels a request that hangs, so your loader doesn't spin forever.
See it in code
Walk through the code
1async function getCourses() {2 try {3 const res = await fetch("/api/courses", {4 signal: AbortSignal.timeout(5000),5 });6 if (!res.ok) throw new Error(`Request failed: ${res.status}`);7 return await res.json();8 } catch (err) {9 console.error(err);10 showToast("Couldn't load courses. Try again?");11 return [];12 }13}1/4Send the request and cancel it automatically if there's no answer within 5 seconds.
Without the res.ok check, a 404 error page would go straight into res.json() and fail with a confusing parsing error.
Save yourself the pain
Common mistakes
Oops
Assuming fetch throws when the server returns 404 or 500.
Do this instead
Check res.ok (or res.status) yourself and throw if it's false.
Oops
Forgetting the Content-Type header when sending JSON.
Do this instead
Add headers: { "Content-Type": "application/json" } and send body: JSON.stringify(data).
Your mission
Build a mini quote loader
Quick check
The server replies with status 500. What does a plain await fetch(url) do?
Go deeper
- 1Fetch a list of users from a free test API and show their names on the page.
- 2Check response.ok and handle errors, since fetch doesn't reject on a 404.
- 3Show a loading message while waiting for the response.
Also part of these roadmaps
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.