Using node-fetch with TypeScript (3 examples)

Updated: December 29, 2023 By: Guest Contributor Post a comment

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.