Stop 10 · API IntegrationTopics · 3/16

Fetch

Part of the Frontend Developer Roadmap

In short

fetch is built into every modern browser and into Node, so it needs no install. It's simple, but it has a couple of traps that catch almost every beginner.

The native browser API for HTTP requests — no install required, Promise-based, but more manual than Axios for things like JSON parsing and error handling.

The jaadu opens a delivered parcel at the post office and peeks inside with a magnifying glass.

Think of it like this

Speed Post with a tracking slip

Speed Post confirms your parcel was delivered, not that the person inside liked it. fetch is similar: it only fails if the request couldn't reach the server. A 404 or 500 still counts as 'delivered', so you must open the reply and check.

Watch it happen

The 404 trap

Your code
Server

POST /api/courses

1/4fetch sends the POST with a JSON body and a Content-Type header.

The big ideas

What you need to know

It returns a promise

fetch gives you a promise of a Response. Use await or .then() to get it.

Two steps to the data

First you get the Response, then you call res.json() (also async) to read the body.

Check res.ok yourself

res.ok is true only for 200 to 299 statuses. fetch won't throw for a 404 or 500.

Cancel with AbortController

Pass a signal to fetch so you can cancel a request the user no longer needs.

See it in code

Walk through the code

ts
1async function createCourse(name: string) {2  const res = await fetch("/api/courses", {3    method: "POST",4    headers: { "Content-Type": "application/json" },5    body: JSON.stringify({ name }),6  });7 8  if (!res.ok) {9    throw new Error(`Server said ${res.status}`);10  }11  return res.json();12}

1/3A POST needs the method, a JSON Content-Type header and a stringified body.

For a POST, send a method, a Content-Type header and a JSON string as the body. Then check res.ok before reading anything.

Save yourself the pain

Common mistakes

Oops

Wrapping fetch in try/catch and thinking that handles 404s.

Do this instead

catch only sees network failures. Add if (!res.ok) throw ... so bad statuses reach catch too.

Oops

Passing a plain object as body: { name }.

Do this instead

Convert it with JSON.stringify() and set the Content-Type header to application/json.

Your mission

Fetch, fail and cancel

~20 min

Quick check

fetch() gets a 404 response. What does the promise do?

Go deeper

  1. 1Write a small wrapper around `fetch` that throws on non-OK responses.
  2. 2Compare the amount of boilerplate needed vs the same request in Axios.
  3. 3Learn `AbortController` for cancelling in-flight fetch requests.

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.

Download
InsideEdge