React.js

Next.js HTTP GET Request

Next.js is a React framework that allows developers to build server-side rendered (SSR) or statically generated web applications. Let’s explore how to initiate an HTTP GET call in Next.js and view the results.

1. Overview of Next.js

1.1 Key Features of Next.js

  • Server-side Rendering (SSR): Next.js enables server-side rendering out of the box, improving performance and SEO by generating HTML on the server for each request.
  • Static Site Generation (SSG): Next.js supports static site generation, allowing developers to pre-render pages at build time for improved performance and lower hosting costs.
  • Automatic Code Splitting: Next.js automatically splits JavaScript code into smaller chunks, ensuring that only necessary code is loaded for each page, resulting in faster load times.
  • Client-side Routing: Next.js provides a simple and intuitive routing system that allows for seamless navigation between pages without full page reloads.
  • API Routes: With Next.js, developers can easily create API routes to handle server-side logic and data fetching, making it ideal for building full-stack applications.
  • Zero Configuration: Next.js requires minimal setup and configuration, allowing developers to focus on writing code rather than configuring tools.
  • Hot Module Replacement (HMR): Next.js supports hot module replacement, enabling instant updates to the application code during development without the need for full page reloads.
  • Static File Serving: Next.js serves static assets like images, stylesheets, and fonts efficiently, improving overall performance.
  • Dynamic Imports: Next.js allows for dynamic imports, enabling lazy loading of components and routes, further optimizing performance.

1.2 Advantages of Using Next.js

Next.js offers several advantages for web development:

  • Improved Performance: Next.js optimizes performance through server-side rendering, automatic code splitting, and static site generation.
  • Enhanced SEO: Server-side rendering and static site generation improve SEO by ensuring that search engines can crawl and index content effectively.
  • Streamlined Development: Next.js simplifies development with features like zero configuration, hot module replacement, and built-in routing.
  • Scalability: Next.js is highly scalable and can be used to build small projects as well as large-scale applications.
  • Flexibility: Next.js provides flexibility in choosing between server-side rendering, static site generation, or a combination of both based on project requirements.
  • Full-stack Capabilities: With support for API routes, Next.js enables developers to build full-stack applications using a single framework.

2. Code Example

Creating a “Hello, World!” application in Next.js is straightforward. Next.js is a React framework that enables server-side rendering and simplifies the creation of React applications. Here’s a simple step-by-step guide to creating a “Hello, World!” application in Next.js:

2.1 Setting up Node Js

Ensure that Node.js and npm (Node Package Manager) are installed on your system. It’s recommended to use a Node.js version greater than 18 when working with Next.js.

2.2 Creating a Backend application

To understand the Next.js and http api interaction we need to create a backend application using the express.js framework. You can refer to this article to understand and download a sample backend application.

2.3 Create a new Next.js app

You have the option to initiate a new Next.js application using the create-next-app command, a tool provided by the Next.js team.

npx create-next-app next-http-app

Executing this command will generate a fresh directory named next-http-app and initialize a new Next.js project within it. The command will present prompts for inputs (such as TypeScript or JavaScript app and using default CSS or SCSS), allowing you to make decisions based on your requirements.

2.4 Navigate into the project directory

Navigate to the project directory and modify the src/app/page.tsx typescript file. By default, Next.js creates a simple homepage. Open this file and replace its contents with the following:

"use client";

import { useEffect, useState } from "react";

type User = {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  gender: string;
  phone: string;
};

const Home = () => {
  const [data, setData] = useState<User[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch("http://localhost:10091/users");
        const responseData = await res.json();
        setData(responseData.info);
      } catch (err) {
        console.error(err);
      }
    };
    fetchData();
  }, []);

  return (
    <main>
      <div>
        <h1>Next.js - HTTP GET call example</h1>
        <table>
          <thead>
            <tr>
              <th>first name</th>
              <th>last name</th>
              <th>email address</th>
              <th>gender</th>
              <th>phone number</th>
            </tr>
          </thead>
          <tbody>
            {data.map((user) => (
              <tr key={user.id}>
                <td>{user.first_name}</td>
                <td>{user.last_name}</td>
                <td>{user.email}</td>
                <td>{user.gender}</td>
                <td>{user.phone}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </main>
  );
};

export default Home;

2.4.1 Explanation

This code is a React component called Home, which fetches user data from an API endpoint and displays it in a table. Here’s a breakdown of what it does:

  • It imports useEffect and useState hooks from the React library.
  • It defines a type User which represents the structure of user data.
  • Inside the Home component:
    • It initializes a state variable data using the useState hook. This state variable will hold an array of User objects.
    • It uses the useEffect hook to perform side effects in the component. In this case, it fetches data from the API when the component mounts ([] as the second argument ensures that the effect runs only once after the initial render).
    • The fetchData function sends a GET request to the specified URL (http://localhost:10091/users) to retrieve user data. Once the data is received, it is parsed as JSON and stored in the data state variable using setData.
    • If an error occurs during the fetch operation, it is logged to the console.
  • In the JSX returned by the component:
    • It renders a heading (<h1>) indicating it’s an example of an HTTP GET call using Next.js.
    • It renders a table with headers for the user attributes (first name, last name, email address, gender, and phone number).
    • It maps over the data array and renders a table row (<tr>) for each user object. Each user’s attributes (first_name, last_name, email, gender, and phone) are displayed in separate table cells (<td>).
    • Each table row is assigned a unique key based on the user’s id.
  • Finally, it exports the Home component as the default export.

Next.js set up the default CSS. You can disable the default CSS by commenting on the code in the src/app/globals.css file.

3. Run the development server

npm run dev

This command will start the development server, and you’ll be able to see your Next.js app running on http://localhost:3000. If the port is already in use, Next.js will automatically switch to a different port. If you need to specify a custom port, update the scripts tag in the package.json file as shown below.

"scripts": {
    "dev": "next dev -p 8200",
    "build": "next build",
    "start": "next start -p 8202",
    "lint": "next lint"
  }

Once the developer server is up you can see the changes reflected in your browser at http://localhost:3000.

HTTP GET call in Next.js
Fig. 1: App demo

4. Conclusion

In conclusion, understanding the process of sending an HTTP GET call to a backend application and observing the subsequent results is crucial for modern web development. This fundamental operation forms the backbone of many interactions between frontend and backend systems, enabling the exchange of data and facilitating dynamic content rendering. By delving into the intricacies of HTTP requests and responses, developers gain a deeper comprehension of how information flows across the web, empowering them to build robust and efficient applications. Additionally, mastering this aspect of web development fosters enhanced problem-solving skills and paves the way for creating seamless user experiences. Ultimately, the ability to effectively utilize HTTP GET calls contributes to the creation of responsive, interactive, and feature-rich web applications that meet the evolving needs of users in today’s digital landscape.

5. Download the Code

This tutorial provided instructions on initiating an HTTP GET request to a backend application and viewing the results.

Download
You can download the full source code of this example here: HTTP GET call in Next.js

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button