Blog
What is `isomorphic-unfetch`?

What is `isomorphic-unfetch`?

In this article, we review what isomorphic-unfetch is. We will look at:

  1. isomorphic-unfetch package

  2. isomorphic-unfetch usage in Meshery codebase.

I study patterns used in an open source project found on Github Trending. For this week, I reviewed some parts of Meshery codebase and wrote this article.

isomorphic-unfetch package

Switches between unfetch & node-fetch for client & server.

Fork differences:

  1. On Node, node-fetch is always used instead of global.fetch. This is a workaround this undici bug which is negatively affecting many versions of Node and Next.js.

  2. Don’t polyfill, leave global.fetch alone.

  3. Applies a patch on node-fetch-cjs to this node-fetch bug by following this PR. Then we inline node-fetch-cjs into the built version of server.js, so that it will contain our patched version of node-fetch-cjs.

Install

$ npm i isomorphic-unfetch

Usage

import fetch from 'isomorphic-unfetch';

fetch('/foo.json')
  .then( r => r.json() )
  .then( data => {
    console.log(data);
  });

I picked this above information from the npm package page

I also found better explanation in this StackOverflow question: What is the difference between isomorphic-fetch and isomorphic-unfetch npm packages

The isomorphic-fetch is built on top of whatwg-fetch and isomorphic-unfetch is built on top of unfetch. What both of them are doing is switching between node-fetch and the other package for client and server.

So their difference is only in the client and the question reduces to: What’s the difference between whatwg-fetch and unfetch?

The whatwg-fetch package is an almost complete polyfill for fetch API, but the unfetch is built with “bundle size” as the first priority in mind (like the other packages written by Jason Miller such as preact). The unfetch only supports a subset of the full fetch API. However, it’s great if you just need simple requests in your application.

A good strategy for new applications is to use unfetch at first, and replace it with whatwg-fetch if you need any feature (such as streaming) which is not supported in unfetch.

isomorphic-unfetch usage in Meshery codebase.

You will find the following import in meshery/ui/lib/data-fetch.js

import fetch from 'isomorphic-unfetch';

const dataFetch = (url, options = {}, successFn, errorFn) => {
...

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Want to learn from open-source? Solve challenges inspired by open-source projects.

References:

  1. https://www.npmjs.com/package/@plasmicapp/isomorphic-unfetch

  2. https://github.com/meshery/meshery/blob/master/ui/lib/data-fetch.js#L3

  3. https://stackoverflow.com/questions/61483803/what-is-the-difference-between-isomorphic-fetch-and-isomorphic-unfetch-npm-p