Nuances of fetching data on the client and on the server
Servers and clients have different libraries that allow you to load data. In the browser, there are XMLHttpRequest
and WhatWG
Fetch API, and, on the server side, there are the Node.js default http
and https
packages. In order to load data universally (such as in an isomorphic manner,both on the server and on the client, using the same code base), we need to install an additional network layer.
There are two options here:
- The firstoption is to simply polyfill the WhatWG Fetch API, since it's natively available on the client side in browsers.
In order to do that, we should install a package:
$ npm install isomorphic-fetch --save
And then, we require/import it anywhere beforefetch()
usages:
import 'isomorphic-fetch'; (async () => { const res = await fetch(...); // already polyfilled })();
- Another way is to use a universal library that will take care of the network layer; for example, the most popular one...