Fetch & Working with APIs

Beginner · 6 min

Making HTTP requests from the browser with fetch, handling JSON and errors, and what CORS actually protects against.

Before thisDOM Manipulation & Events

Web Dev Simplified · 6 min

Fetch & Working with APIs

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • fetch() returns a promise that resolves once the response headers arrive — the body still has to be read separately with a second asynchronous step, like response.json().
  • fetch only rejects on a network failure; a 404 or 500 response is still a 'successful' fetch, so you must check response.ok yourself to treat it as an error.
  • CORS is a browser-enforced rule, not a server-side security feature — it exists to stop a malicious page from silently reading responses from a site where the victim is logged in.
  • A CORS error in the console means the response arrived but the browser withheld it from your script, because the server's Access-Control-Allow-Origin header didn't permit your page's origin.
  • Real UIs need three states for every fetch — loading, success, and error — because a network request can be slow or fail outright, and the page has to look intentional either way.

A page is not an island

Almost nothing interesting on the modern web lives entirely in the HTML the server first sent you. A weather widget needs current conditions, a search box needs results, a dashboard needs numbers that change by the minute. All of that means the browser has to go back out over the network, after the page has already loaded, and ask some server for more data. fetch() is the browser’s built-in tool for making that request from JavaScript.

What fetch actually does

fetch('/api/users') kicks off an HTTP request and returns a promise. That promise resolves once the response’s headers have arrived — not once the whole body has downloaded, and not once you have usable data. This two-step shape trips people up constantly, so it’s worth sitting with: you get a Response object first, and then you call a method on it, like response.json(), to actually read and parse the body — which is itself asynchronous, because the body might still be streaming in.

const response = await fetch('/api/users');
const data = await response.json();

Two awaits, two separate asynchronous steps. Skipping the second one and trying to use response directly as if it were your data is one of the most common first mistakes with fetch.

The error handling trap

Here’s the detail that catches almost everyone at least once: fetch’s promise only rejects when the network itself fails — DNS doesn’t resolve, the connection drops, there’s no route to the server. A response that comes back as a 404 or a 500 is, as far as fetch is concerned, a perfectly successful round trip: a server answered, and it answered with “not found” or “I broke.” That means this code is wrong:

fetch('/api/users')
  .then(r => r.json())
  .catch(() => showError()); // never runs for a 404

The fix is to check response.ok (true for any 2xx status) or response.status yourself, and throw or branch explicitly:

const response = await fetch('/api/users');
if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}
const data = await response.json();

Combine that with a real try/catch around the whole thing, and you can distinguish “the network died” from “the server answered with bad news” — both of which a real UI needs to show differently to a user.

Loading, success, error: the three states

Every fetch call in a UI needs three visual states, not one. There’s the moment before the data arrives, when you should show a spinner or skeleton rather than a blank gap. There’s success, when you render the data. And there’s failure — network or HTTP-level — when you show something more useful than a silently empty section. Skipping the loading state is what makes an app feel like it’s lagging or broken for a beat; skipping the error state is what makes it feel broken for good when a request fails.

Same-origin policy: the rule that makes CORS necessary

To understand CORS, you first need the rule it’s an exception to: the same-origin policy. By default, a script running on https://example.com cannot read the response of a request it makes to https://bank.com. This isn’t a server-side rule — it’s enforced entirely by the browser, and it exists because the browser automatically attaches your cookies to a request, including your login session. Without this restriction, any malicious page you happen to visit could quietly fetch https://bank.com/account-balance in the background using your logged-in session, and read the response — you’d never know.

CORS: an explicit exception, not a bug

CORS (Cross-Origin Resource Sharing) is how a server opts back into letting other origins read its responses. A server adds an Access-Control-Allow-Origin header naming which origins are allowed, and the browser checks that header before handing the response body to your script. If it’s missing or doesn’t match, the browser throws away the response and you get the famous console error.

This is the single most important thing to internalize about a CORS error: the request usually succeeded. The server very likely received it, processed it, and sent back a valid response. The error isn’t “your request failed to reach the server” — it’s “the browser got an answer back and refused to let your code see it,” because the server never said your page’s origin was allowed to read it. Fixing a CORS error almost always means changing the server’s response headers, not your client-side fetch call — there’s no clever flag you can pass to fetch to make the browser skip this check, because the whole point is that your script shouldn’t get to decide that for itself.

Check yourself

  1. 01Why does fetching a URL that returns a 404 not land in your .catch() block?

    Because fetch only treats the request as failed when the network itself breaks down — a 404 is a complete, valid HTTP response, so the promise still resolves and you have to check response.ok or response.status yourself.

  2. 02What problem does the same-origin policy exist to prevent?

    It stops a script loaded from one site from reading data back from a different site using the viewer's existing login — without it, a malicious page could silently fetch your bank's page while you're logged in and read the response.

  3. 03When you see a CORS error, did the request actually fail to reach the server?

    Usually not — the server often processed the request and sent a response just fine; the browser received it and then refused to hand it to your JavaScript because the response's CORS headers didn't allow your page's origin.

  4. 04Why do you need to call response.json() as a separate step after fetch() resolves?

    Because fetch resolves as soon as the response headers are in, before the body has necessarily finished downloading, so reading and parsing the body is a second asynchronous operation.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark