HTTP Client Performance

HTTP Client/Server Definition

TLDR

Use Fetch if you need performance and reduce build size. or other option is to use redaxios or Alova. Use Axios if you already used.

HTTP (Hypertext Transfer Protocol)

HTTP is a fundamental protocol used for communication on the World Wide Web. It defines how data (such as HTML documents, images, videos, etc.) is transmitted between a client (usually a web browser) and a server (usually a web server). HTTP operates over the Internet and relies on a request-response model.

Client

A client is any device or software that initiates communication with a server to request information or services. In the context of the web, a client is typically a web browser (such as Chrome, Firefox, or Safari) that users interact with to view web pages. When you type a URL into your browser’s address bar or click a link, your browser acts as the client and sends an HTTP request to the server hosting the requested content.

Server

A server is a computer or software that responds to requests from clients by providing data or services. In the context of the web, a web server hosts websites, applications, or other resources. When the server receives an HTTP request from a client, it processes the request, retrieves the requested data (such as an HTML page or an image), and sends back an HTTP response to the client.

Axios V.S. Fetch

Axios is a promise-based HTTP client that works both in the browser and in a Node.js environment. It simplifies the process of making HTTP requests by providing a consistent and easy-to-use API.

Fetch is a built-in browser feature that allows you to make HTTP requests without any additional installation. or the extended by web framework such Next.js in this article

Performance Comparison

Fetch is significant improvement compared to Axios. And Axios build size is 30.5KB in axios@1.6.8.

  • Average turn around time for call api.
    • Axios: 90ms
    • Fetch: 40ms

Backend API Code

Create 10k random value and return it.

import { NextRequest, NextResponse } from 'next/server';

export async function GET(request:NextRequest) {

    const ldata = 
        {
            "data": [
                // Generate 1000 items
                ...Array.from(Array(10000).keys()).map(i => ({
                    "id": i,
                    "name": `Item ${i}`,
                    "value": Math.floor(Math.random() * 100)
                }))
            ]
        }

    try {
        // const result = {"message": "Hello World!"}
        const result = {"message": ldata }

        return NextResponse.json({ result }, { status: 200 });
    } catch (error) {
        return NextResponse.json({ message: "Error", error }, { status: 500 });
    }
}

Axios Code

import React from 'react'
import axios from 'axios'

const getSomeData = async (): Promise<any> => {
    try {
        const res = await axios.get(`http://localhost:3000/api/sample`);
        if (res.status !== 200) {
            throw new Error("Failed to fetch");
        }
        return res.data;
    } catch (error) {
        console.log("Error loading", error);
    }
}

const Page = async () => {
    const startTime = new Date().getTime()
    const data:any = await getSomeData()
    const endTime = new Date().getTime()

    return (
        <div className="p-16 text-xl">
            <p>axios method: get ramdom id {data.result.message.data[0].value}</p>
            <p>Time taken: {endTime - startTime} ms</p>
        </div>
  )
}

export default Page

Fetch Code

import React from 'react'

const getSomeData = async (): Promise<any> => {
    try {
        const res = await fetch("http://localhost:3000/api/sample")
        if (!res.ok) {
            throw new Error("Failed to fetch");
        }
        return res.json();
    } catch (error) {
        console.log("Error loading", error);
    }
}

const Page = async () => {
    const startTime = new Date().getTime()
    const data:any = await getSomeData()
    const endTime = new Date().getTime()

    return (
        <div className="p-16 text-xl">
            <p>fetch method: get ramdom id {data.result.message.data[0].value}</p>
            <p>Time taken: {endTime - startTime} ms</p>
        </div>
  )
}

export default Page

Publish Date: 2024-05-20, Update Date: 2024-05-20