Next.js - Data Fetching



Data Fetching

Next.js comes with all the data fetching capabilities of React.js. It supports multiple data-fetching methods, such as static generation (SSG), server-side rendering (SSR), and client-side fetching. Next.js ensure security, by fetching data on server-side and then releasing it to the client-side on request. The server-side data fetching provide better performance and SEO results by reducing client-side javascript code

Types of Data Fetching

Next.js offers three types of data fetching methods:

Server-side Fetching

In server-side fetching, the data is fetched on the server-side and then released to the client-side. It is two types.

  • Static Site Generation
  • Server-side Rendering

Static Site Generation

The static generation is the default behavior in Next.js. In this method, Next.js generates these pages at build time and reuses them for every request. The static generation is the recommended method for pages that do not require frequently updated data.

In the following example, we implement a static page, which will fetch data from an API and display it on the page. We use the fetch function to make a request to the API and then use the json method to parse the response as JSON.

export async function getStaticProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
  const post = await res.json();

  return {
    props: { post },
  };
}

export default function Post({ post }) {
  return (
    <div>
        <h1>{post.title}</h1>
        <p>{post.body}</p>
    </div>
  );
}

Server-side Rendering

In server-side rendering, the data will be fetched for every request to server. This method is recommended for pages that require frequently updated data.

In the example below, we used the getServerSideProps function to fetch data from an API and pass it to the page as props. This ensures that the user will see the latest data on every request.

export async function getServerSideProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    const post = await res.json();

    return {
        props: { post },
    };
}

export default function Post({ post }) {
    return (
      <div>
          <h1>{post.title}</h1>
          <p>{post.body}</p>
      </div>
    );
}

Client-side Fetching

In client-side fetching, the data fetching will happen on user's browser. This is not a recommended approach as it affect performance and SEO results of website.

The example below uses, the react useEffect hook to fetch data from an API and set it to the state. The data is then used to render the page.

"use client";

import { useEffect, useState } from 'react';

export default function Post() {
    const [post, setPost] = useState(null);

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(res => res.json())
        .then(data => setPost(data));
    }, []);

    if (!post) return <p>Loading...</p>;

    return (
        <div>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
        </div>
    );
}

Incremental Static Regeneration

Incremental Static Regeneration is a feature in Next.js by which the static pages can be updated after deployment without requiring a full rebuild. This means that pages can be statically generated at build time and then incrementally updated as needed while the application is running.

In the following example, we will create a page that fetches data from an API and displays it on the page. Here we set revalidate: 10, this ensures that the page updates at most every 10 seconds when a new request comes in.

// File: pages/index.js

import { useEffect } from 'react';
import { getServerSideProps } from 'next';

export async function getStaticProps() {
    const data = await fetchData(); // Fetch data from API 
  
    return {
      props: { data },
      revalidate: 10, // Regenerate the page every 10 seconds
    };
  }

  export default function Home({ data }) {
    return (
        <div>
            <h1>Home Page</h1>
            <p>This is the home page.</p>
            <div>{JSON.stringify(data)}</div>
        </div>
    );
}
Advertisements