Chapter 47 of 49

JavaScript Fetch API

Almost every modern web app talks to a server. When you open a food delivery app, it loads restaurants from a server. When you post a comment, the comment is sent to a server. When you search for a product, the results come from a server.

In JavaScript, the standard way to make these network requests is the Fetch API. We've already had quick previews of fetch() in the Browser APIs and JSON chapters. Now that you understand promises and async/await, we can learn it properly.

Here's what a typical request looks like:

async function getUser() {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
    const user = await response.json();

    console.log(user.name);
}

getUser();

Output:

Leanne Graham

The examples in this chapter use JSONPlaceholder (jsonplaceholder.typicode.com), a free fake REST API for practice. You can run them in the browser console or in Node.js 18 or later, where fetch() is also built in.


What is the Fetch API?

The Fetch API is a built-in JavaScript interface for making HTTP requests. The fetch() function sends a request and returns a promise that resolves to a Response object.

Before fetch(), developers used an older API called XMLHttpRequest (XHR), which was callback-based and clumsy. fetch() is promise-based, so it works naturally with .then() and await.


A Quick HTTP Refresher

Every network request has two halves:

Your code ──── Request ────►  Server
          (method, URL, headers, body)

Your code ◄─── Response ────  Server
          (status code, headers, body)

HTTP Methods

Method

Used to

Example

GET

Read data (the default)

Get a list of products

POST

Create new data

Register a new user

PUT

Replace existing data completely

Replace a whole profile

PATCH

Update part of existing data

Change only the phone number

DELETE

Remove data

Delete a comment

Status Codes

Range

Meaning

Common examples

2xx

Success

200 OK, 201 Created, 204 No Content

3xx

Redirect

301 Moved Permanently, 304 Not Modified

4xx

Client error (problem with the request)

400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found

5xx

Server error

500 Internal Server Error, 503 Service Unavailable


Making a GET Request, Step by Step

Getting JSON data with fetch() is a two-step process:

async function getUser() {
    // Step 1: send the request and wait for the response headers
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");

    // Step 2: read the body and parse it as JSON
    const user = await response.json();

    console.log(user.name);
    console.log(user.email);
    console.log(user.address.city);
}

getUser();

Output:

Leanne Graham
Sincere@april.biz
Gwenborough

Why two awaits?

  1. fetch() resolves as soon as the server sends back the status and headers. The body may still be downloading.

  2. response.json() reads the rest of the body and parses it as JSON. That also takes time, so it returns another promise.

The same thing with .then() looks like this:

fetch("https://jsonplaceholder.typicode.com/users/1")
    .then(response => response.json())
    .then(user => console.log(user.name))
    .catch(error => console.log("Error:", error.message));

Output:

Leanne Graham

The Response Object

The Response object tells you what the server sent back:

Property

Meaning

response.ok

true if the status is in the range 200-299

response.status

The status code, e.g. 200 or 404

response.statusText

The status message, e.g. "OK" (often an empty string over HTTP/2)

response.headers

A Headers object; use response.headers.get("name")

response.url

The final URL (after any redirects)

And methods to read the body, each returning a promise:

Method

Returns

response.json()

The body parsed as JSON

response.text()

The body as a string

response.blob()

Binary data (for images, files)

response.formData()

The body as FormData

response.arrayBuffer()

Raw binary data

async function inspect() {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/1");

    console.log(response.ok);
    console.log(response.status);
    console.log(response.headers.get("content-type"));
}

inspect();

Output:

true
200
application/json; charset=utf-8

The body can only be read once. After calling response.json(), calling response.json() or response.text() again throws a TypeError (the body has already been used). If you need it twice, store the result in a variable, or call response.clone() before reading.


The Biggest Gotcha: fetch() Doesn't Reject on HTTP Errors

This surprises almost everyone. Try to fetch a user that doesn't exist:

async function getMissingUser() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users/9999");
        console.log("No error thrown!");
        console.log(response.status, response.ok);
    } catch (error) {
        console.log("Caught:", error.message);
    }
}

getMissingUser();

Output:

No error thrown!
404 false

The server answered with 404 Not Found, but the catch block didn't run.

The promise returned by fetch() only rejects when the request couldn't be completed at all (no internet, DNS failure, blocked by CORS, or aborted). A 404 or 500 is still a valid response from the server, so the promise fulfills.

Situation

What fetch() does

200 OK

Fulfills, response.ok is true

404 Not Found, 500 Server Error

Fulfills, response.ok is false

No network, DNS failure, CORS blocked

Rejects with a TypeError

Request aborted or timed out

Rejects with an AbortError or TimeoutError

So you must check response.ok yourself, and usually throw an error if it's false.


A Reusable, Safe Fetch Helper

In real projects, you'll often write a small helper so you don't repeat the checks everywhere:

async function getJSON(url) {
    const response = await fetch(url);

    if (!response.ok) {
        throw new Error(`Request failed with status ${response.status}`);
    }

    return response.json();
}

async function main() {
    try {
        const user = await getJSON("https://jsonplaceholder.typicode.com/users/2");
        console.log("Found:", user.name);

        const missing = await getJSON("https://jsonplaceholder.typicode.com/users/9999");
        console.log("Found:", missing.name);   // never reached
    } catch (error) {
        console.log("Error:", error.message);
    }
}

main();

Output:

Found: Ervin Howell
Error: Request failed with status 404

Now HTTP errors and network errors both end up in the same catch block.


Sending Data with POST

To send data, pass a second argument to fetch(): an options object. As we saw in the JSON chapter, objects must be converted to JSON text with JSON.stringify():

async function createPost() {
    const newPost = {
        title: "Learning Fetch",
        body: "fetch() makes HTTP requests easy.",
        userId: 1
    };

    const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(newPost)
    });

    const created = await response.json();

    console.log(response.status);
    console.log(created.id);
    console.log(created.title);
}

createPost();

Output:

201
101
Learning Fetch

The server responded with 201 Created and returned the new post with an id. (JSONPlaceholder only pretends to save it, so it always returns id: 101.)

The most common options are:

Option

Purpose

method

"GET" (default), "POST", "PUT", "PATCH", "DELETE"

headers

Extra information, like Content-Type or Authorization

body

The data to send (a string, FormData, Blob, etc.). Not allowed with GET.

signal

An AbortSignal for cancelling the request

credentials

Whether to send cookies: "same-origin" (default), "include", or "omit"

PATCH, PUT, and DELETE

These work the same way; only the method changes:

async function updateAndDelete() {
    const patchResponse = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title: "Updated title" })
    });
    const updated = await patchResponse.json();
    console.log(patchResponse.status, updated.title);

    const deleteResponse = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
        method: "DELETE"
    });
    console.log(deleteResponse.status, deleteResponse.ok);
}

updateAndDelete();

Output:

200 Updated title
200 true

Query Parameters

Many APIs accept filters in the URL, after a ?, like /posts?userId=1&_limit=3. Instead of gluing strings together by hand, use the built-in URL and URLSearchParams classes, which handle special characters (spaces, &, etc.) correctly:

async function getPosts() {
    const url = new URL("https://jsonplaceholder.typicode.com/posts");
    url.searchParams.set("userId", 1);
    url.searchParams.set("_limit", 3);

    console.log(url.toString());

    const response = await fetch(url);
    const posts = await response.json();

    console.log(posts.length);
    console.log(posts.map(p => p.id));
}

getPosts();

Output:

https://jsonplaceholder.typicode.com/posts?userId=1&_limit=3
3
[ 1, 2, 3 ]
const params = new URLSearchParams({ q: "laptop bag", page: 2 });

console.log(params.toString());

Output:

q=laptop+bag&page=2

Headers and Authentication

Protected APIs usually expect a token in the Authorization header:

const token = localStorage.getItem("authToken");

const response = await fetch("/api/profile", {
    headers: {
        "Authorization": `Bearer ${token}`,
        "Accept": "application/json"
    }
});

(This is browser code: localStorage was covered in the storage chapter, and it runs inside an async function or module.)

Sending Form Data

To submit a form (including file uploads), you can send a FormData object directly. new FormData(form) is a built-in browser object that collects every named field of a <form> (including selected files) as key-value pairs:

const form = document.querySelector("#signup-form");

form.addEventListener("submit", async (event) => {
    event.preventDefault();

    const response = await fetch("/api/signup", {
        method: "POST",
        body: new FormData(form)   // don't set Content-Type yourself here
    });

    console.log(response.ok ? "Signed up!" : "Signup failed");
});

When the body is FormData, don't set the Content-Type header manually. The browser sets it to multipart/form-data with the correct boundary automatically.


Timeouts and Cancelling Requests

fetch() has no timeout by default. A slow server could keep your app waiting for a very long time. We control this with an AbortSignal.

Timeout with AbortSignal.timeout()

async function loadWithTimeout() {
    try {
        // httpbin's /delay/5 endpoint waits 5 seconds before responding
        const response = await fetch("https://httpbin.org/delay/5", {
            signal: AbortSignal.timeout(1000)   // give up after 1 second
        });
        console.log(response.status);
    } catch (error) {
        console.log(error.name);
    }
}

loadWithTimeout();

Output:

TimeoutError

Cancelling with AbortController

Sometimes the user should be able to cancel, for example by clicking a "Cancel" button, or when they type a new search before the old one finishes. Use an AbortController:

const controller = new AbortController();

async function search() {
    try {
        const response = await fetch("https://httpbin.org/delay/5", {
            signal: controller.signal
        });
        console.log(response.status);
    } catch (error) {
        if (error.name === "AbortError") {
            console.log("Request was cancelled");
        } else {
            console.log("Error:", error.message);
        }
    }
}

search();

// Cancel after 200 ms (in a real app: when the user clicks "Cancel")
setTimeout(() => controller.abort(), 200);

Output:

Request was cancelled

How it was stopped

error.name

controller.abort()

"AbortError"

AbortSignal.timeout(ms) expired

"TimeoutError"


Multiple Requests in Parallel

Exactly as in the async/await chapter, independent requests should run together using Promise.all():

async function getJSON(url) {
    const response = await fetch(url);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
}

async function loadDashboard() {
    const base = "https://jsonplaceholder.typicode.com";

    const [user, posts, todos] = await Promise.all([
        getJSON(`${base}/users/1`),
        getJSON(`${base}/posts?userId=1`),
        getJSON(`${base}/todos?userId=1`)
    ]);

    console.log(user.name);
    console.log("Posts:", posts.length);
    console.log("Todos:", todos.length);
}

loadDashboard();

Output:

Leanne Graham
Posts: 10
Todos: 20

If any request fails, Promise.all() rejects. Use Promise.allSettled() if you want to show whatever loaded successfully.


A Practical Example: Showing Data on a Page

Let's combine fetch with DOM manipulation. A good UI handles three states: loading, success, and error.

<button id="load-btn">Load Users</button>
<p id="status"></p>
<ul id="user-list"></ul>
const button = document.querySelector("#load-btn");
const statusText = document.querySelector("#status");
const list = document.querySelector("#user-list");

button.addEventListener("click", async () => {
    statusText.textContent = "Loading...";
    button.disabled = true;
    list.innerHTML = "";

    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users");

        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }

        const users = await response.json();

        for (const user of users) {
            const li = document.createElement("li");
            li.textContent = `${user.name} (${user.email})`;
            list.appendChild(li);
        }

        statusText.textContent = `Loaded ${users.length} users`;
    } catch (error) {
        statusText.textContent = `Could not load users: ${error.message}`;
    } finally {
        button.disabled = false;
    }
});

Clicking the button shows "Loading...", then fills the list with 10 users and shows "Loaded 10 users". If the network fails, a friendly error message appears instead. Notice we used textContent, not innerHTML, to insert data from the server, which protects against injecting unwanted HTML.


CORS in One Minute

If you fetch from a different origin (a different domain, port, or protocol than your page), the browser applies a security rule called CORS (Cross-Origin Resource Sharing). The server must explicitly allow your origin by sending headers like Access-Control-Allow-Origin. If it doesn't, the browser blocks your code from reading the response, and fetch() rejects with a TypeError.

  • CORS is enforced by the browser, not by fetch() itself. The same request from Node.js has no CORS restriction.

  • You can't fix a CORS error from frontend code alone. The server needs to send the right headers (or you call the API through your own backend).


fetch() vs Alternatives

Feature

fetch()

XMLHttpRequest

Axios (library)

Built in

Yes (browsers, Node.js 18+)

Yes (browsers only)

No, install it

Style

Promises

Events/callbacks

Promises

Rejects on 4xx/5xx

No, check response.ok

No

Yes

JSON parsing

Manual: await response.json()

Manual

Automatic

Timeout / cancel

AbortSignal

timeout, abort()

timeout option, AbortSignal

For most projects, plain fetch() plus a small helper like getJSON() is all you need.


Common Mistakes

  • Forgetting the second await: const data = response.json(); gives you a promise, not the data. Write await response.json().

  • Not checking response.ok: a 404 or 500 doesn't throw. Your code would then try to use an error page as data.

  • Forgetting JSON.stringify(): passing an object directly as body sends the useless string "[object Object]".

  • Forgetting the Content-Type header when sending JSON, so the server doesn't know how to read the body.

  • Reading the body twice: the body is a stream and can only be consumed once.

  • Calling response.json() on an empty response (for example, 204 No Content), which throws a SyntaxError. Check the status first.

  • Running independent requests one after another instead of with Promise.all().


Interview Tips

  • "Does fetch() reject on a 404?" No. It only rejects on network failures, CORS blocks, and aborts. Check response.ok or response.status.

  • "Why does getting JSON need two awaits?" fetch() resolves when headers arrive; response.json() reads and parses the body, which is a separate async step.

  • "How do you cancel or time out a request?" Pass a signal from an AbortController or AbortSignal.timeout(ms).

  • "What is CORS?" A browser security rule; the server must allow cross-origin requests with Access-Control-Allow-* headers.

  • "PUT vs PATCH?" PUT replaces the whole resource; PATCH updates only the fields you send.

Practice ideas:

  • Build a search box that fetches results as the user types, cancelling the previous request with AbortController.

  • Write fetchWithRetry(url, attempts) that retries on network errors or 5xx responses.

  • Build a small "To-Do" page that loads, adds (POST), and deletes (DELETE) items using JSONPlaceholder.

Conclusion

The Fetch API is how JavaScript talks to servers. The essential pattern is:

async function getJSON(url) {
    const response = await fetch(url);           // 1. send request, get Response

    if (!response.ok) {                          // 2. check the HTTP status
        throw new Error(`HTTP ${response.status}`);
    }

    return response.json();                      // 3. read and parse the body
}

And for sending data:

fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
});

Remember the key rules:

fetch() rejects only on network errors, CORS blocks, and aborts
404 / 500  → still fulfills, so check response.ok
Body       → read once with json(), text(), blob()...
Timeouts   → AbortSignal.timeout(ms) or AbortController
Parallel   → await Promise.all([...])

With promises, async/await, JSON, and fetch(), you now have everything you need to build pages that load and send real data.