DEV Community

Cover image for The NodeJS 18 Fetch API
Andrew Baisden
Andrew Baisden

Posted on

The NodeJS 18 Fetch API

NodeJS 18 introduced some new cool features and one of the most useful ones is the built in Fetch API. What this means is that we longer need to use 3rd party npm packages like node-fetch because the functionality is now native and baked into Node. That's one less dependency that we need to install so our node_modules folders should be a little lighter.

Before you can use the latest NodeJS features like the Fetch API you first need to check that you are running the latest version of Node on your computer. Run the command node -v in your console to see which version you have running. If its less than 18 then you need to upgrade before you can use these new features.

Using the Fetch API

If you are already familiar with using the Fetch API in the browser when developing JavaScript applications, then this syntax should be easy to understand. We finally have a native solution for fetching data on the backend using JavaScript.

const getAPI = async () => {
    const res = await fetch('https://pokeapi.co/api/v2/pokemon/');

    if (res.ok) {
        const data = await res.json();

        console.log(data);
    }
};

getAPI();
Enter fullscreen mode Exit fullscreen mode

Let's create a practical example so you can see one potential use case. Navigate to a directory and then copy and paste the code below into your command line to scaffold a project.

mkdir node-backend-fetch
cd node-backend-fetch
npm init -y
npm i express nodemon
touch app.js
mkdir controllers routes
touch controllers/pokemon.js
touch routes/pokemon.js
Enter fullscreen mode Exit fullscreen mode

Open the project in your code editor and then copy the code below into their corresponding files.

controllers/pokemon.js

exports.getPokemon = async (req, res) => {
    const api = await fetch('https://pokeapi.co/api/v2/pokemon/');

    if (api.ok) {
        const data = await api.json();

        console.log(data);

        try {
            res.json(data);
        } catch (error) {
            console.log(error);
        }
    }
};

exports.getPokemonMoves = async (req, res) => {
    const api = await fetch('https://pokeapi.co/api/v2/move/');

    if (api.ok) {
        const data = await api.json();

        console.log(data);

        try {
            res.json(data);
        } catch (error) {
            console.log(error);
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

routes/pokemon.js

const express = require('express');

const pokemonController = require('../controllers/pokemon');

const router = express.Router();

router.get('/pokemon', pokemonController.getPokemon);

router.get('/pokemon-moves', pokemonController.getPokemonMoves);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

app.js

const express = require('express');

const pokemonRoute = require('./routes/pokemon');

const app = express();

app.use('/', pokemonRoute);

const port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`));
Enter fullscreen mode Exit fullscreen mode

package.json

Add these run scripts.

"scripts": {

"start": "node app.js",

"dev": "nodemon app.js"

},
Enter fullscreen mode Exit fullscreen mode

Double check to make sure that you are using Node 18 and then run the command npm run dev to start the backend server.

If you go to this route http://localhost:3000/pokemon you should have a list of Pokemon returned in json. The data is also logged to the console.

And if you go to this route http://localhost:3000/pokemon-moves you should have a list of Pokemon moves which is also returned as json. Like in the other example the data is logged to the console too.

Final Thoughts

This was a brief introduction to using the NodeJS 18 Fetch API. To learn more check out the official announcement.

Top comments (14)

Collapse
 
lexlohr profile image
Alex Lohr

For libraries, I found a rather nice pattern to allow users to only install node-fetch if they need it:

// package.json
{
  "peerDependencies": {
    "node-fetch": "*"
  },
  "peerDependenciesMeta": {
    "node-fetch": {
      "optional": true
    }
  }
}

// Run before you use fetch:
if (!globalThis.fetch) {
  Object.assign(globalThis, {
    fetch: (...args: any[]) => {
      try {
        const fetch = require("node-fetch");
        Object.assign(globalThis, { fetch });
        return fetch(...args);
      } catch (e) {
        console.warn(
          '"\x1b[33m⚠️ package missing to run fetch on the server.\n Please run:\x1b[0m\n\nnpm i node-fetch\n"'
        );
        Object.assign(globalThis, { fetch: () => Promise.reject() });
        return Promise.reject();
      }
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

This way, users get a helpful message if they forget to install node-fetch and you can avoid superfluous dependencies.

Collapse
 
suchintan profile image
SUCHINTAN DAS

Thanks Andrew πŸ‘¨, for sharing this information.

Can't wait to try it out on the system πŸ‘.

One suggestion πŸ’­. Can you explain the changes that are being introduced on the new version of fetch api compared to the previous version ✍.

I think it would make the blog a full packed information about the topic and would also increase the understanding of people who can't have time to look on the documentation to know about the information β„Ή.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Hmm the official documentation is probably the best place to learn about it developer.mozilla.org/en-US/docs/W....

I believe that the NodeJS implemented of the fetch API is the same as the one we already use in the browser.

Collapse
 
suchintan profile image
SUCHINTAN DAS

Thanks Andrew πŸ‘,

Let me go through the documentation to know what amazing stuffs we have on this new version of Node JS 🀠

Collapse
 
judis07 profile image
Arvind M

Clean and Concise.πŸ‘πŸ‘πŸ‘

Collapse
 
andrewbaisden profile image
Andrew Baisden

Thanks much appreciated.

Collapse
 
dinerdas profile image
Diner Das

Glad I came across this.

Collapse
 
vareksun profile image
Varek

Very detailed, thanks.

Collapse
 
snelson1 profile image
Sophia Nelson

Well described post

Collapse
 
surajondev profile image
Suraj Vishwakarma

NiceπŸ”₯, Now we don't have to depend on any other library for fetching data. Btw great article , Andrew.

Collapse
 
strivecode profile image
Abdul-Razak

Wawu that was timely. You have saved me a bunch of time. Thank you!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Sure no problem.

Collapse
 
spock123 profile image
Lars Rye Jeppesen

Great article but it would have been nice if you also showed POST requests, not entirely simple GET

Collapse
 
upsylondev profile image
UPSYLON DEVELOPPEMENT

Hello. cool stuff & article
but how manage headers with this api ?