DEV Community

Cover image for Introduction to the javascript fetch() Api
Rajesh Dhiman
Rajesh Dhiman

Posted on • Originally published at


Introduction to the javascript fetch() Api

The Fetch api is used to fetch data or resources from a server. It allows us to retrieve data from a URL without having to do a full page refresh. The Fetch api is an improvement over the XMLHttpRequest API (XHR).

Here is a basic example of XMLHttpRequest. Example from MDN docs.

    function reqListener() { 
        var data = JSON.parse(this.responseText); 
    function reqError(err) { 
        console.log('Fetch Error :-S', err); 
     var oReq = new XMLHttpRequest(); 
     oReq.onload = reqListener; 
     oReq.onerror = reqError;'get', './api/some.json', true); 

And a simple fetch request looks like:

    .then( function(response) {
       if (response.status !== 200) {
          console.log('Looks like there was a problem. Status Code: ' + response.status); 
        // Examine the text in the response 
      }).catch(function(err) { 
        console.log('Fetch Error :-S', err); 

fetch method accepts the path to a resource that we want to retrieve as a parameter, in this case, ./api/some.json. It returns a promise that resolves to a response object.
The response object represents the response to a request. It contains the response body and also useful properties and methods.
Note: It doesn't matter if the response is bad response (like 404) it will still resolve.

A fetch promise only rejects if the request is incomplete, so we must always check the validity of the response. We can check for inadequate responses using response.ok
Fetch responses are represented as ReadableStreams and must be read to access the body of the response. Response objects have body interface methods like .json(),.blob(), etc. to do this.

Type Of Requests

By default, fetch uses the GET method, which retrieves a specific resource. But fetch can also be performed using other HTTP methods.
The fetch method receives a second optional parameter, init. This parameter allows us to pass the configuration of the fetch request, including the request method, cache mode, credentials, and more.

Example from Google codelab.

  fetch('examples/words.txt', {
    method: 'HEAD'
  }).then( function(response) {
       if (response.status !== 200) {
          console.log('Looks like there was a problem. Status Code: ' + response.status); 

    const url = response.url;
    const size = response.headers.get('content-length');
    console.log(`${url} is ${size} bytes`);
      }).catch(function(err) { 
        console.log('Fetch Error :-S', err); 

In this example, we set the fetch request method to HEAD using the init parameter. HEAD requests are just like GET requests, except the body of the response is empty. This kind of request can be used when all we want is metadata about a file, but we don’t need to transport all of the file’s data.


Fetch (and XMLHttpRequest) follows the same-origin policy. This means that browsers restrict cross-origin HTTP requests from within scripts.

A cross-origin request occurs when one domain (for example requests a resource from a separate domain (for instance

Note: Cross-origin request restrictions are often confusing. Various resources like images, stylesheets, and scripts, are fetched across domains (i.e., cross-origin). However, these are exceptions to the same-origin policy. Cross-origin requests are still restricted from within scripts.

Using no-cors mode allows fetching an opaque response. This allows us to get a response but prevents accessing the response with JavaScript. The response, however, can still be consumed by other APIs or cached by a service worker.

Request Headers

Fetch also supports modifying request headers. We can use headers interface to created Headers object and pass that object in the init parameter.

Example from Google codelab.

 const customHeaders = new Headers({
    'Content-Type': 'application/json',
    'Content-Length': 'kittens', // Content-Length can't be modified!
    'X-Custom': 'hello world',
  fetch('http://localhost:5000/', {
    method: 'POST',
    // body: formData,
    body: JSON.stringify({ lab: 'fetch', status: 'fun' }),
    headers: messageHeaders

The Header interface enables the creation and modification of Headers objects. Some headers, like Content-Type can be modified by fetch. Others, like Content-Length, are guarded and can't be modified (for security reasons).

For more information you can also check out

Top comments (2)

maciejcieslik profile image
Maciej Cieslik • Edited

Is fetch js or browser api?

paharihacker profile image
Rajesh Dhiman

Fetch is a javascript API. Browsers need to support it to enable us to use fetch.


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!