Smart GeekSmart Geek
HomeArticlesCategories
Smart Geek

Thoughtful articles on technology, design, and culture in multiple languages.

Navigation

  • Home
  • Articles
  • Categories
  • About
  • Contact
  • Privacy Policy
  • RSS Feed

© 2026 Smart Geek. All rights reserved.

BlogProgrammingHow to Use the Fetch API in JavaScript
ProgrammingHow to

How to Use the Fetch API in JavaScript

The moment you learn how to pull live data from a server into your JavaScript app, everything you can build changes completely. The Fetch API is how that happens and once it clicks, you'll wonder how you ever built anything without it.

Sayed Bin FahadSayed Bin Fahad
July 13, 202610 min read31 views
how to use fetch api in javascriptjavascript fetch api tutorialfetch api examples 2026fetch api vs xmlhttprequestjavascript api calls beginner guide

The moment you learn how to pull live data from a server into your JavaScript app, everything you can build changes completely. The Fetch API is how that happens and once it clicks, you'll wonder how you ever built anything without it.


What Is the Fetch API?

The Fetch API is a built-in JavaScript interface that lets you make HTTP requests like loading data from a server or submitting form data using a clean, Promise-based syntax. It's available natively in every modern browser and in Node.js (since v18), which means you don't need to install anything to start using it. You write fetch(url), and JavaScript handles the network request for you.

The Fetch API replaced the older XMLHttpRequest method as the standard way to make API calls in JavaScript, and it's now one of the core tools every JavaScript developer needs to know.


Why Did the Fetch API Replace XMLHttpRequest?

The Fetch API replaced XMLHttpRequest because it is significantly cleaner to read, write, and reason about. XMLHttpRequest (often abbreviated as XHR) required verbose, callback-heavy code where you had to attach event listeners and manually check response states, and the resulting code was hard to follow even for experienced developers. I still remember staring at XHR code early in my learning journey and genuinely not being sure where the actual data was coming back.

Fetch uses Promises, which means you can chain .then() calls or use async/await to write requests that read almost like plain English. Same outcome, far less mental overhead.


How Does Fetch API Compare to XMLHttpRequest?

Feature

Fetch API

XMLHttpRequest

Syntax simplicity

Clean, minimal, Promise-based

Verbose, event-listener-heavy

Promise-based

Yes, native Promise support

No, requires callbacks

Streaming support

Yes, via ReadableStream

Limited

Browser support

All modern browsers + Node.js 18+

All browsers including legacy IE

Error handling

Manual, only rejects on network failure

Manual, also only fails on network errors

Default behavior on HTTP errors

Does NOT throw on 404/500, must check response.ok

Same, HTTP errors don't trigger onerror

The most important row in that table is the last two, both Fetch and XHR behave the same way on HTTP errors, and that surprises most beginners. More on this in the mistakes section below.


How Do You Make a Basic GET Request with Fetch?

A basic GET request with Fetch takes one line, you pass a URL to fetch() and it returns a Promise that resolves with the server's response.

//javascript
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => console.log(response));

Running this in your browser console gives you a Response object, but not the actual data yet. The response body hasn't been read. That's the next step.


How Do You Extract Data from a Fetch Response Using .json()?

To get the actual data out of a Fetch response, you call .json() on the response object. This reads the response body and parses it as JSON, returning another Promise that resolves with the parsed data.

//javascript
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => {
    console.log(data.title);
    console.log(data.body);
  });

The two-step process, first fetch(), then .json() confuses almost every beginner at least once. The reason is that fetch() resolves as soon as the headers arrive, not when the entire body has loaded. Calling .json() is what actually reads and parses the body.


How Do You Send a POST Request with Fetch?

A POST request with Fetch requires passing a second argument an options object that specifies the method, headers, and body you want to send.

//javascript
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'My New Post',
    body: 'This is the content of the post.',
    userId: 1
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Three things to notice here: the method tells the server you're sending data, the Content-Type header tells it you're sending JSON, and JSON.stringify() converts your JavaScript object into the JSON string the server expects to receive. Forget any of these and the server will either reject the request or receive garbled data.


How Do You Handle Errors Properly in Fetch?

Error handling in Fetch requires two separate checks. One for network failures and one for HTTP errors. Fetch only rejects its Promise when a network error occurs (no internet, DNS failure, request blocked). It does NOT reject on HTTP error status codes like 404 or 500. You have to check response.ok manually.

//javascript
fetch('https://jsonplaceholder.typicode.com/posts/999')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Something went wrong:', error));

The response.ok property is true when the status code is in the 200–299 range, and false for everything else. Manually throwing an error inside the .then() block when !response.ok is the standard pattern for catching 4xx and 5xx responses.


What Is the Difference Between async/await and .then() with Fetch?

async/await and .then() chains do the same thing. They're just two different syntaxes for working with Promises. async/await tends to be cleaner for more complex requests, especially when you need to conditionally do things based on the response. Here's the exact same POST request written both ways:

Using .then() chains:

//javascript
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'Hello', body: 'World', userId: 1 })
})
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
    return response.json();
  })
  .then(data => console.log('Created:', data))
  .catch(error => console.error('Failed:', error));

Using async/await with try/catch:

//javascript
async function createPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: 'Hello', body: 'World', userId: 1 })
    });

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

    const data = await response.json();
    console.log('Created:', data);

  } catch (error) {
    console.error('Failed:', error);
  }
}

createPost();

Both versions handle errors correctly. Most modern JavaScript codebases prefer async/await for readability, especially when chaining multiple requests but .then() is perfectly valid and you'll see it often in older tutorials and open-source code.


How Do You Test a Fetch API Request Without Building a Full App?

The fastest way to test a Fetch request is your browser's DevTools. Open any webpage, hit F12 (or Cmd+Option+I on Mac), click the Console tab, and paste a fetch() call directly in. It runs immediately, and you can see the result right there.

For the network details response headers, status codes, timing, and the raw response body. The Network tab in DevTools is your best friend. Every fetch request your page makes appears there in real time. Click on any request to inspect exactly what was sent and received.

For practicing fetch calls, use free public APIs that don't require authentication or an API key.

The Best Practice API for Beginners: JSONPlaceholder JSONPlaceholder (jsonplaceholder.typicode.com) is a free, fake REST API built specifically for practicing fetch calls. It supports GET, POST, PUT, PATCH, and DELETE requests, returns realistic-looking JSON data (posts, users, comments, todos), and never actually modifies anything. So you can't break it. Every example in this guide uses it. Open your browser console right now and run fetch('https://jsonplaceholder.typicode.com/users').then(r => r.json()).then(console.log). Your first successful API call takes about ten seconds.


What Are the Most Common Fetch API Mistakes?

Why Does My Fetch Request Return an Object Instead of Real Data?

This happens when you forget to call .json() on the response. fetch() returns a Response object, not the data itself. You always need that second step: response.json(). It's the single most common mistake beginners make with Fetch, and it happens to almost everyone at least once.

Why Doesn't Fetch Throw an Error on a 404 Response?

Fetch only rejects on network-level failures, not HTTP error status codes. A 404 or 500 response is still a valid HTTP response from the server's perspective. The request succeeded in reaching the server, so Fetch considers its job done. You must check response.ok (or response.status) inside your .then() block and throw an error manually if the status indicates failure.

What Causes a CORS Error with Fetch?

CORS (Cross-Origin Resource Sharing) errors happen when you try to fetch data from a domain that hasn't explicitly allowed your domain to access it. This is a server-side restriction, the API you're calling needs to include the right Access-Control-Allow-Origin headers in its response. You can't fix a CORS error purely from the client side; the fix belongs on the server or API you're requesting from.

Why Is My POST Request Being Received as Plain Text?

If you're sending JSON but not including 'Content-Type': 'application/json' in your headers, the server receives your stringified data as plain text and likely won't parse it correctly. Always pair JSON.stringify() in the body with the correct Content-Type header in every POST, PUT, or PATCH request.


FAQ

Does the Fetch API Work in All Browsers?

Fetch works in all modern browsers like Chrome, Firefox, Safari, Edge, and Opera all support it fully. The one exception is Internet Explorer, which has no Fetch support at all. Since IE officially reached end-of-life and its market share is now negligible, this is rarely a concern for new projects. Fetch is also natively available in Node.js since version 18 without importing any library.

What Is the Difference Between Fetch and Axios?

Axios is a third-party JavaScript library (installed via npm) that wraps HTTP requests with additional features on top of what Fetch provides natively. The key practical differences are that Axios automatically parses JSON responses (no .json() step needed), automatically throws errors on non-2xx HTTP status codes (no response.ok check needed), and has built-in request cancellation and timeout support. Fetch is built into the browser and requires no installation, but Axios trades a small bundle size for a significantly smoother developer experience on more complex projects.

Why Does Fetch Not Throw an Error on 404 or 500 Responses?

Fetch considers any response from the server, including 404 and 500 responses. A successfully completed request, because the network connection worked and the server did respond. A Fetch Promise only rejects when there's a network-level failure, like no internet connection, DNS resolution failure, or the request being blocked. To handle HTTP errors, you check response.ok or response.status inside your .then() handler and throw an error manually if needed.

Can You Cancel a Fetch Request?

Yes, using the AbortController API. You create an AbortController, pass its signal to the fetch options, and call controller.abort() whenever you need to cancel the request.

//javascript
const controller = new AbortController();

fetch('https://jsonplaceholder.typicode.com/posts', {
  signal: controller.signal
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => {
    if (error.name === 'AbortError') {
      console.log('Request was cancelled');
    }
  });

// Cancel after 3 seconds
setTimeout(() => controller.abort(), 3000);

This is particularly useful for cancelling requests when a user navigates away from a page or types a new search term before the previous one finishes loading.

How Do You Send Cookies with a Fetch Request?

By default, Fetch does not include cookies in cross-origin requests. To send cookies, add credentials: 'include' to your options object.

/javascript
fetch('https://api.example.com/profile', {
  credentials: 'include'
})
  .then(response => response.json())
  .then(data => console.log(data));

Use credentials: 'same-origin' (the default in most browsers now) if you only need to send cookies to the same domain as your page. credentials: 'include' is for cross-origin requests where the server explicitly allows it via CORS headers.


Wrapping Up

The Fetch API is one of those tools that feels slightly awkward for the first hour and then becomes second nature for every project after that the two-step response pattern, the response.ok check, and the async/await wrapper are really all you need to handle 90% of real API calls confidently. Start with JSONPlaceholder, run through each example above in your browser console, and you'll have a solid foundation for working with any API you encounter.

Sayed Bin Fahad

Sayed Bin Fahad

Contents

  • What Is the Fetch API?
  • Why Did the Fetch API Replace XMLHttpRequest?
  • How Does Fetch API Compare to XMLHttpRequest?
  • How Do You Make a Basic GET Request with Fetch?
  • How Do You Extract Data from a Fetch Response Using .json()?
  • How Do You Send a POST Request with Fetch?
  • How Do You Handle Errors Properly in Fetch?
  • What Is the Difference Between async/await and .then() with Fetch?
  • How Do You Test a Fetch API Request Without Building a Full App?
  • What Are the Most Common Fetch API Mistakes?
  • Why Does My Fetch Request Return an Object Instead of Real Data?
  • Why Doesn't Fetch Throw an Error on a 404 Response?
  • What Causes a CORS Error with Fetch?
  • Why Is My POST Request Being Received as Plain Text?
  • FAQ
  • Does the Fetch API Work in All Browsers?
  • What Is the Difference Between Fetch and Axios?
  • Why Does Fetch Not Throw an Error on 404 or 500 Responses?
  • Can You Cancel a Fetch Request?
  • How Do You Send Cookies with a Fetch Request?
  • Wrapping Up

Tags

Programming

Related Articles

Fix 'MySQL Shutdown Unexpectedly' in XAMPP: Step-by-Step Guide
Programming

Fix 'MySQL Shutdown Unexpectedly' in XAMPP: Step-by-Step Guide

Fix the frustrating “MySQL Shutdown Unexpectedly” error in XAMPP with this clear, step-by-step guide. Learn the most common causes from port conflicts to corrupted data files and follow simple solutions to get your local server running smoothly again in minutes.

mysqlxamppphp
Sayed Bin Fahad
Apr 9, 2026 5 min
How to Install Python on Windows 11 (Step-by-Step)
Programming

How to Install Python on Windows 11 (Step-by-Step)

Learn how to install Python on Windows 11 step-by-step. Covers download, PATH setup, version check, and common errors. Updated May 2026 for beginners.

pythonwindows 11install python
Sayed Bin Fahad
May 3, 2026 9 min
Programming

Python vs JavaScript: Which Should You Learn First?

You've decided to finally learn programming, and now you're stuck on the first decision that feels way bigger than it should Python or JavaScript? I've watched dozens of beginners freeze at this exact crossroads, so let's settle it with facts instead of hype.

javascriptpythonweb
Sayed Bin Fahad
Jun 18, 2026 8 min