Sunday, March 3, 2024

The best way to use the Fetch API in Node.js, Deno, and Bun — SitePoint


On this article, we’ll take a look at use the Fetch API with Node.js, Deno, and Bun.

Desk of Contents

Fetch API vs XMLHttpRequest

Fetching information by way of an HTTP request is key internet software exercise. You might have made such calls within the browser, however the Fetch API is natively supported in Node.js, Deno, and Bun.

In a browser, you would possibly request info from a server so you may show it and not using a full display screen refresh. That is usually referred to as an Ajax request or a single web page software (SPA). Between 1999 and 2015, XMLHttpRequest was the one possibility — and stays so if you wish to present file add progress. XMLHttpRequest is a reasonably clunky callback-based API, nevertheless it permits fine-grained management and, regardless of the title, it’ll deal with responses in codecs apart from XML — akin to textual content, binary, JSON, and HTML.

Browsers have applied the Fetch API from 2015. It’s an easier, simpler, extra constant, promise-based various to XMLHttpRequest.

Your server-side code can also wish to make HTTP requests — usually to name APIs on different servers. From their first launch, each the Deno and Bun runtimes usefully replicated the browser’s Fetch API in order that related code may run on each the consumer and server. Node.js required a third-party module akin to node-fetch or axios till February 2022, when model 18 added the usual Fetch API. It’s nonetheless thought of experimental, however now you can use fetch() in every single place with equivalent code usually.

A Primary Fetch Instance

This easy instance fetches response information from a URI:

const response = await fetch('https://instance.com/information.json');

The fetch() name returns a promise which resolves with a Response object offering details about the outcome. You’ll be able to parse the HTTP response physique right into a JavaScript object utilizing the promise-based .json() technique:

const information = await response.json();



Shopper-side vs Server-side Fetch

The API could also be equivalent throughout platforms, however browsers implement restrictions when making client-side fetch() requests:

  • Cross-origin useful resource sharing (CORS)

    Shopper-side JavaScript can solely talk with API endpoints inside its personal area. A script loaded from https://domainA.com/js/primary.js can name any service at https://domainA.com/, akin to https://domainA.com/api/ or https://domainA.com/information/.

    It’s inconceivable to name a service on https://domainB.com/ — until that server permits entry by setting an HTTP Entry-Management-Enable-Origin header.

  • Content material Safety Coverage (CSP)

    Your websites/apps can set a Content material-Safety-Coverage HTTP header or meta tag to manage permitted belongings in a web page. It may well forestall unintended or malicious injection of scripts, iframes, fonts, photographs, movies, and so forth. For instance, setting default-src 'self' stops fetch() requesting information outdoors its personal area (XMLHttpRequest, WebSocket, server-sent occasions, and beacons are additionally restricted).

Server-side Fetch API calls in Node.js, Deno, and Bun have fewer restrictions, and you may request information from any server. That stated, third-party APIs might:

  • require some form of authentication or authorization utilizing keys or OAuth
  • have most request thresholds, akin to no multiple name per minute, or
  • make a industrial cost for entry

You need to use server-side fetch() calls to proxy client-side requests so you may keep away from CORS and CSP points. That stated, bear in mind to be a conscientious internet citizen and don’t bombard providers with hundreds of requests that might take them down!

Customized Fetch Requests

The instance above requests information from the URI https://instance.com/information.json. Under the floor, JavaScript creates a Request object, which represents the total particulars of that request akin to the tactic, headers, physique, and extra.

fetch() accepts two arguments:

  • the useful resource – a string or URL object, and
  • an elective choices parameter with additional request settings

For instance:

const response = await fetch('https://instance.com/information.json', {
   technique: 'GET',
   credentials: 'omit',
   redirect: 'error',
   precedence: 'excessive'
});

The choices object can set following properties in Node.js or client-side code:

property values
technique GET (the default), POST, PUT, PATCH, DELETE, or HEAD
headers a string or Headers object
physique generally is a string, JSON, blob, and so on.
mode same-origin, no-cors, or cors
credentials omit, same-origin, or embody cookies and HTTP authentication headers
redirect comply with, error, or guide dealing with of redirects
referrer the referring URL
integrity subresource integrity hash
sign an AbortSignal object to cancel the request

Optionally, you may create a Request object and move it to fetch(). This can be sensible should you can outline API endpoints prematurely or wish to ship a collection related requests:

const request = new Request('https://instance.com/api/', {
  technique: 'POST',
  physique: '{"a": 1, "b": 2, "c": 3}',
  credentials: 'omit'
});

console.log(`fetching ${ request.url }`);
const response = await fetch(request);

Dealing with HTTP Headers

You’ll be able to manipulate and look at HTTP headers within the request and response utilizing a Headers object. The API might be acquainted should you’ve used JavaScript Maps:


const headers = new Headers({
  'Content material-Sort': 'textual content/plain',
});


headers.append('Authorization', 'Primary abc123');


headers.set('Content material-Sort', 'software/json');


const sort = headers.get('Content material-Sort');


if (headers.has('Authorization')) {

   
   headers.delete('Authorization');

}


headers.forEach((worth, title) => {
  console.log(`${ title }: ${ worth }`);
});


const response = await fetch('https://instance.com/information.json', {
   technique: 'GET',
   headers
});


response.headers.forEach((worth, title) => {
  console.log(`${ title }: ${ worth }`);
});

Fetch Promise Resolve and Reject

You would possibly presume a fetch() promise will reject when an endpoint returns a 404 Not Discovered or related server error. It doesn’t! The promise will resolve, as a result of that decision was profitable — even when the outcome wasn’t what you anticipated.

A fetch() promise solely rejects when:

  • you make an invalid request — akin to fetch('httttps://!invalidURL/');
  • you abort the fetch() request, or
  • there’s a community error, akin to a connection failure

Analyzing Fetch Responses

Profitable fetch() calls return a Response object containing details about the state and returned information. The properties are:

property description
okay true if the response was profitable
standing the HTTP standing code, akin to 200 for achievement
statusText the HTTP standing textual content, akin to OK for a 200 code
url the URL
redirected true if the request was redirected
sort the response sort: primary, cors, error, opaque, or opaqueredirect
headers the response Headers object
physique a ReadableStream of physique content material (or null)
bodyUsed true if the physique has been learn

The next Response object strategies all return a promise, so it’s best to use await or .then blocks:

technique description
textual content() returns the physique as a string
json() parses the physique to a JavaScript object
arrayBuffer() returns the physique as an ArrayBuffer
blob() returns the physique as a Blob
formData() returns the physique as a FormData object of key/worth pairs
clone() clones the response, usually so you may parse the physique in numerous methods

const response = await fetch('https://instance.com/information.json');


if ( response.okay && response.headers.get('Content material-Sort') === 'software/json') {

   
   const obj = await response.json();

}

Aborting Fetch Requests

Node.js received’t day out a fetch() request; it may run ceaselessly! Browsers can even wait between one and 5 minutes. You must abort fetch() below regular circumstances the place you’re anticipating a fairly fast response.

The next instance makes use of an AbortController object, which passes a sign property to the second fetch() parameter. A timeout runs the .abort() technique if fetch doesn’t full inside 5 seconds:


const
  controller = new AbortController(),
  sign = controller.sign,
  timeout = setTimeout(() => controller.abort(), 5000);

attempt {

  const response = await fetch('https://instance.com/slowrequest/', { sign });

  clearTimeout(timeout);

  console.log( response.okay );

}
catch (err) {

  
  console.log(err);

}

Node.js, Deno, Bun, and most browsers launched since mid-2022 additionally help AbortSignal. This gives an easier timeout() technique so that you don’t need to handle your personal timers:

attempt {

  
  const response = await fetch('https://instance.com/slowrequest/', {
    sign: AbortSignal.timeout( 5000 ),
  });

  console.log( response.okay );

}
catch (err) {

  
  console.log(err);

}

Efficient Fetches

Like all asynchronous, promise-based operation, it’s best to solely make fetch() calls in collection when the enter of a name is determined by the output of a earlier one. The next code doesn’t carry out in addition to it may as a result of every API name should await the earlier one to resolve or reject. If every response takes one second, it’ll take a complete of three seconds to finish:


const response1 = await fetch('https://example1.com/api/');
const response2 = await fetch('https://example2.com/api/');
const response3 = await fetch('https://example3.com/api/');

The Promise.allSettled() technique runs guarantees concurrently and fulfills when all have resolved or rejected. This code completes on the velocity of the slowest response. It is going to be 3 times quicker:

const information = await Promise.allSettled(
  [
    'https://example1.com/api/',
    'https://example2.com/api/',
    'https://example3.com/api/'
  ].map(url => fetch( url ))
);

information returns an array of objects the place:

  • every has a standing property string of "fullfilled" or "rejected"
  • if resolved, a worth property returns the fetch() response
  • if rejected, a cause property returns the error

Abstract

Until you’re utilizing a legacy model of Node.js (17 or beneath), the Fetch API is obtainable in JavaScript on each the server and consumer. It’s versatile, simple to make use of, and constant throughout all runtimes. A 3rd-party module ought to solely be needed should you require extra superior performance akin to caching, retries, or file dealing with.



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles