Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 156 Β· Asynchronous JavaScript

Fetching Data with fetch()

Use fetch() to load and send data in JavaScript. Read JSON responses, check status codes, handle network errors, set headers and make POST requests.

Almost every modern web page talks to a server after it loads: a weather widget asks for the forecast, a shop checks stock levels, a form saves without reloading the page. The browser's built-in tool for this is fetch(). You give it a URL, it returns a promise, and that promise gives you a response you can read as JSON, text or binary data.

fetch() is the same in every modern browser, in Node.js (version 18 and later), Deno and Bun, so what you learn here works almost everywhere JavaScript runs. Combined with async and await, a complete request often takes just two lines.

About the examples on this page. The editors run in a locked-down sandbox with no server to talk to, so the live demos fetch data: URLs and Blob URLs (data that lives inside the page) or use a small fake server that returns real Response objects. Your code reads them with exactly the same methods you'd use for a real API: response.ok, response.status, response.json() and so on. Swap in a real URL such as https://api.example.com/users, and nothing else changes.

Your first request

Calling fetch(url) starts a request and returns a promise. When the server's reply starts arriving, the promise fulfills with a Response object. Reading the body is a second asynchronous step, because the body may still be downloading: response.json() returns another promise that gives you the parsed data.

JS Fetch and parse JSON

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Those two awaits are the shape of almost every fetch: wait for the response, then wait for the body.

The Response object

A Response tells you everything about the server's reply:

Property or method What it gives you
response.ok true when the status is in the 200–299 range
response.status The HTTP status code, such as 200, 404 or 500
response.statusText The status message, such as "Not Found" (often empty over HTTP/2)
response.headers A Headers object; use .get("Content-Type")
response.url The final URL, after any redirects
response.json() A promise for the body parsed as JSON
response.text() A promise for the body as a string
response.blob() A promise for the body as a Blob (images, files)

The body can be read only once. After await response.json(), calling response.text() throws a TypeError saying the body is already used. If you really need it twice, call response.clone() first and read each copy separately.

You can also build a Response yourself with new Response(body, { status, headers }). That's how service workers and test code produce fake replies, and it's what the fake server on this page does.

Errors: fetch only rejects on network failure

This is the most important rule about fetch(), and it surprises almost everyone:

  • If the request can't be completed at all, because the user is offline, the domain doesn't exist or the browser blocks it (for example by CORS), the promise rejects with a TypeError.
  • If the server does answer, even with 404 Not Found or 500 Internal Server Error, the promise fulfills. An HTTP error is still a valid response.

So you must check response.ok yourself. The next demo uses a small fake server: a function shaped exactly like fetch() that waits a moment and returns real Response objects with different status codes.

JS Checking response.ok

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Response.json(data, options) is a shortcut that creates a response with a JSON body and the right Content-Type header. It's supported in all current browsers and Node.js; new Response(JSON.stringify(data), ...) does the same thing the long way.

A reusable helper

Most projects wrap this pattern in one small function so the rest of the code can simply await getJSON(url):

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

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

  return response.json();
}

try {
  const forecast = await getJSON("https://api.example.com/forecast?city=Oslo");
  showForecast(forecast);
} catch (error) {
  showMessage("Couldn't load the forecast. Please try again.");
}

The single catch now covers every way the request can fail: no network, an HTTP error status, or a body that isn't valid JSON (response.json() throws a SyntaxError for that).

Reading other kinds of bodies

Not every response is JSON. Use text() for plain text, HTML or CSV, and blob() for binary data such as images. A Blob URL, created with URL.createObjectURL(), points to data held in memory, so it makes a handy stand-in for a file on a server:

JS Text and Blob responses

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Request options: method, headers and body

The second argument to fetch() is an options object. The most common settings are:

  • method: "GET" (the default), "POST", "PUT", "PATCH" or "DELETE".
  • headers: extra HTTP headers, as a plain object or a Headers instance.
  • body: the data to send, usually a JSON string, FormData or URLSearchParams. GET requests can't have a body.
  • signal: an AbortSignal for cancelling, covered in the next lesson.
  • credentials: whether to send cookies on cross-origin requests ("include"); same-origin requests send them by default.

To send JSON, turn the data into a string with JSON.stringify() and tell the server what it is with a Content-Type header:

JavaScript
const response = await fetch("https://api.example.com/comments", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
  },
  body: JSON.stringify({ postId: 42, text: "Great article!" }),
});

if (!response.ok) throw new Error(`HTTP ${response.status}`);
const saved = await response.json(); // many APIs echo back the new record

fetch(url, options) builds a Request object internally. You can create one yourself with the same arguments, which lets you inspect exactly what would be sent without sending anything:

JS Inspecting a POST request

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Header names are case-insensitive, which is why the Headers object lists them in lowercase.

Sending form data

To send a form exactly as the browser would, pass a FormData object as the body. Don't set Content-Type yourself in that case; the browser adds the correct multipart/form-data header, including the boundary string it needs:

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

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const response = await fetch("/api/signup", {
    method: "POST",
    body: new FormData(form),
  });
  // ...check response.ok and show a message
});

A complete loading pattern

User interfaces should show what's happening: a loading state, the data or a friendly error. Here is the full pattern in a small page, again with a fake server so it works in the sandbox. Click the buttons several times; the fake server fails now and then on purpose.

Loading, success and error states

Disabling the button while a request is running prevents duplicate requests, and finally guarantees it's re-enabled whatever happens.

CORS in one paragraph

Browsers only let a page read responses from its own origin (same scheme, host and port) unless the other server opts in. That opt-in is CORS (Cross-Origin Resource Sharing): the server sends headers such as Access-Control-Allow-Origin. When it doesn't, the request may reach the server, but the browser hides the response and fetch() rejects with a TypeError. You can't fix CORS from front-end code; the API has to allow your site, or you call it through your own server. Public APIs designed for browsers already send the right headers.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. The server replies with status 404. What does the promise returned by fetch() do?

    fetch() only rejects when the request can't complete, such as when there is no network. Any HTTP reply, even an error status, fulfills the promise, so check response.ok.
  2. 2. Why does reading JSON take a second await?

    The response promise fulfills when the headers arrive; reading and parsing the body is a separate asynchronous step.
  3. 3. Which options correctly send JSON to an API?

    The body must be a string (or another body type), the method must allow a body, and the Content-Type header tells the server it's JSON.
  4. 4. You called await response.json() and now call await response.text() on the same response. What happens?

    A response body is a stream that can be consumed once. Use response.clone() if you need to read it twice.
  5. 5. Sending a FormData body, what should you do about the Content-Type header?

    The browser generates the correct multipart header, including a boundary that your own header would be missing.

Summary

  • fetch(url, options) returns a promise for a Response; read the body with json(), text() or blob().
  • fetch() rejects only on network-level failure; check response.ok or response.status for HTTP errors.
  • A body can be read once; response.clone() makes a second copy.
  • Send data with method, headers and body: JSON.stringify() plus a JSON Content-Type, or FormData with no manual header.
  • Show loading and error states, disable buttons during requests and clean up in finally.
  • Cross-origin requests need the server's permission through CORS.

Next: Cancelling with AbortController β€” stop requests the user no longer needs and add timeouts.