Saturday, November 16, 2024
Google search engine
HomeLanguagesNext.js Data Fetching Methods

Next.js Data Fetching Methods

Next.js is a React-based full-stack framework that enables functionalities like pre-rendering of web pages. Unlike traditional react app where the entire app is loaded on the client, Next.js allow the web page to be rendered on the server, which is great for performance and SEO. You can learn more about Next.js here.

Next.js provides three data fetching methods and based on these methods, it renders content differently. (You can learn about different rendering methods here.

  1. getStaticProps
  2. getStaticPaths
  3. getServerSideProps

getStaticProps: It preloads all of the data needed for a given page and renders pages ahead of the user’s request at build time. For speedier retrieval, all of the data is cached on a headless CMS. For better SEO performance, the page is pre-rendered and cached. If no other data fetching method is specified, Next.js will use this by default. It is used to implement Static Site Generation and Incremental Site Regeneration.

Properties of getStaticProps: 

  1. It can only be exported from the page file, not the component file.
  2. It only runs on build time.
  3.  It runs on every subsequent request in development mode.
  4. Its code is completely excluded from the client-side bundle.

getStaticPaths: If a page uses getStaticProps and has dynamic routes, it must declare a list of paths that will be statically generated. Next.js will statically pre-render all the paths defined by getStaticPaths when we export a function named getStaticPaths from a page.

Properties of getStaticPaths:

  1.  It can only be exported from a page file.
  2. It is meant for dynamic routes.
  3. Page must also implement getStaticProps.
  4.  It runs only at build time in production.
  5. It runs on every request in development mode.

getServerSideProps: It will pre-render the page on every subsequent request. It is slower as compared to getStaticProps as the page is being rendered on every request. getServerSideProps props return JSON which will be used to render the page all this work will be handled automatically by Next.js. It could be used for calling a CMS, database, or other APIs directly from getServerSideProps. It is used to implement Server Side Rendering.

Properties of getServerSideProps:

  1. It runs on every subsequent request in development as well as production mode.
  2. Its code is excluded from the client-side bundle.
  3. It can only be exported from page file.

When to use which data fetching method: If your page’s content is static or doesn’t change frequently then you should go for getStaticProps as it builds pages on build time hence increasing performance. If your page has dynamic routes then getStaticPaths should be used along with getStaticProps.

But if your website contains a page whose data changes very frequently then you must use getServerSideProps as it fetches fresh data on every request.

Example: We will build a simple Next Js application with three pages of albums, posts, and a users page with dynamic routes. All three pages will implement different data fetching methods. For this example, we will use JSONPlaceholder API to fetch random data.

Run the following command to create a new Next Js application (Make sure you have NPM and node installed) :  

npx create-next-app@latest myproject

When we open our project in a code editor, we see a straightforward project structure. For the scope of this tutorial, we will only focus on /pages directory. We’ll first cleanup the /pages/index.js file. Then we’ll create two new pages albums, posts, and a dynamic routes page /users/[id].

Project Structure: 

 

/pages/index.js – We’ll first cleanup the homepage (index), delete all boilerplate code and add links to all the pages we’ll be implementing for easier Navigation.

Javascript




import React from 'react'
import Link from 'next/link'
const Home = () => {
  
    // This is the home page which will
    // contain links to all other pages
    return (
        <>
            <h1>Hello Geeks</h1>
            <ul>
                <li>
                    getStaticProps : 
                    <Link href={'/about'}>About Page</Link>
                </li>
                <li>
                    getStaticPaths : 
                    <Link href={'/users/1'}>User 1</Link>
                </li>
                <li>
                    getServerSideProps : 
                    <Link href={'/posts'}>Posts Page</Link>
                </li>
            </ul>
        </>
    )
}
  
export default Home


/pages/albums.jsx – Albums page will implement static site generation using getStaticProps, we will export the data fetching method along with the page component. We can send fetched data to the page component using props. Next Js will fetch all the albums at build time before the user’s request.

Javascript




import React from 'react'
  
export const getStaticProps = async () => {
  
    // Fetching data from jsonplaceholder.
    const res = await fetch(
    let allAlbums = await res.json();
  
    // Sending fetched data to the page component via props.
    return {
        props: {
            allAlbums: allAlbums.map((album) => album.title)
        }
    }
}
  
const Albums = ({ allAlbums }) => {
    return (
        <div>
            <h1>All Albums</h1>
            {allAlbums.map((album, idx) => (
                <div key={idx}>{album}</div>))
            }
        </div>
    )
}
  
export default Albums


/pages/posts.jsx – Posts page will implement server-side rendering using getServerSideProps. It’ll fetch posts data and build page at each request made by user., and send fetched data to the component using props.

Javascript




import React from 'react'
  
export const getServerSideProps = async (ctx) => {
  
    // ctx is the context object which contains the request,
    // response and props passed to the page.
  
    // fetching data from jsonplaceholder.
    const res = await fetch(
    let allPosts = await res.json();
  
    // Sending fetched data to the page component via props.
    return {
        props: {
            allPosts: allPosts.map((post) => post.title)
        }
    }
}
  
const Posts = ({ allPosts }) => {
    return (
        <div>
            <h1>All Posts</h1>
            {allPosts.map((post, idx) => (
                <div key={idx}>{post}</div>))}
        </div>
    )
}
  
export default Posts


/pages/users/[id].jsx – Because this is a dynamic page, we must pre-define all of the user Ids so that Next Js can retrieve their data at build time. As a result, we use getStaticPaths and define ten user Ids.

Javascript




import React from "react";
  
export const getStaticProps = async (ctx) => {
  
    // ctx will contain request parameters
    const { params } = ctx;
      
    // We will destructure id from the parameters
    const userId = params.id;
      
    // Fetching user data
    const res = await fetch(
        `https://jsonplaceholder.typicode.com/users/${userId}`
    );
    const userData = await res.json();
  
    // Sending data to the page via props
    return {
        props: {
            user: userData,
        },
    };
};
  
export const getStaticPaths = () => {
      
    // Specifying all the routes to be
    // pre-rendered by next js
    return {
        paths: [
            { params: { id: "1" } },
            { params: { id: "2" } },
            { params: { id: "3" } },
            { params: { id: "4" } },
            { params: { id: "5" } },
            { params: { id: "6" } },
            { params: { id: "7" } },
            { params: { id: "8" } },
            { params: { id: "9" } },
            { params: { id: "10" } },
        ],
        fallback: false,
    };
};
  
const User = ({ user }) => {
    return (
        <>
            <h1>User {user.id}</h1>
            <h2>Name : {user.name}</h2>
            <h2>Email : {user.email}</h2>
        </>
    );
};
  
export default User;


Run the application: Open the terminal and enter the following command.

npm run dev

Output: 

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments