Sling Academy
Home/Node.js/Using node-fetch with TypeScript (3 examples)

Using node-fetch with TypeScript (3 examples)

Last updated: December 29, 2023

Introduction

TypeScript, renowned for its static typing capabilities, has become a staple in modern web development. Pairing TypeScript with node-fetch, a lightweight module that introduces the Fetch API to Node.js, allows developers to make HTTP calls in a more efficient and modular way compared to the traditional XMLHttpRequest. This article demonstrates three examples of using node-fetch in TypeScript, ranging from basic GET requests to more advanced scenarios like handling POST requests with JSON payloads and incorporating error handling.

Setting Up the Project

To begin, let’s set up a TypeScript project and install the required dependencies. Ensure you have Node.js and npm installed. Start by creating a new directory for your project and initializing a new npm package:

mkdir node-fetch-typescript-tutorial
cd node-fetch-typescript-tutorial
npm init -y

Next, install TypeScript, node-fetch, and the necessary type definitions:

npm install typescript node-fetch @types/node-fetch --save

Initialize TypeScript with the default configuration:

npx tsc --init

You should now see a tsconfig.json file in your project directory. Now, let’s dive into the examples.

Examples

Example 1: Simple GET Request

The most basic use case involves performing a GET request to retrieve data. Create a file named get-example.ts and add the following TypeScript code:

import fetch from 'node-fetch';

async function fetchTodos() {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    const todo = await response.json();
    console.log(todo);
}

fetchTodos();

This code fetches data from an API and logs it to the console.

Example 2: POST Request with JSON

For a more complex scenario, consider handling a POST request with JSON. Create a file named post-example.ts and add:

import fetch from 'node-fetch';

interface Post {
    title: string;
    body: string;
    userId: number;
}

async function createPost(postData: Post) {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        body: JSON.stringify(postData),
        headers: { 'Content-Type': 'application/json' }
    });
    const post = await response.json();
    console.log(post);
}

const newPost: Post = {
    title: 'foo',
    body: 'bar',
    userId: 1
};

createPost(newPost);

This segment demonstrates an async function sending a POST request with a JSON-encoded body.

Example 3: Error Handling with Async/Await

Properly managing network and parsing errors is crucial. Here’s how to add error handling to your async functions:

import fetch from 'node-fetch';

async function fetchWithErrorHandling() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/invalid-url');
        if (!response.ok) {
            throw new Error(response.statusText);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Fetching failed:', error.message);
    }
}

fetchWithErrorHandling();

In this case, an error is thrown if the fetch response is not ‘ok’. The error is then caught and logged, illustrating basic error handling in asynchronous TypeScript functions. This practice is vital for dealing with real-world APIs.

Conclusion

Integrating node-fetch with TypeScript enhances the robustness of HTTP calls in Node.js applications by leveraging static typing to catch potential issues at compile time. The progression from simple GET requests to POSTing data, and then to error handling, showcases the effectiveness and clarity TypeScript brings to using the familiar Fetch API pattern. Mastering these techniques in TypeScript with node-fetch lays a solid foundation for building complex applications confidently.

Next Article: Setting Up Docker Compose with Node.js, Express, Sequelize, and MySQL

Previous Article: NodeJS: Search and download images by keyword from Unsplash API

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates