Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptNext.js getStaticPaths() Function

Next.js getStaticPaths() Function

The getStaticPaths() function in NextJS is used to pre-generate static pages for dynamic routes.

For example, we can create a page that has dynamic parameters like `user/[ID]`  and then we can create a static version for every possible value of the dynamic parameter. In our case, if the dynamic parameter ID limits up to 3 we can create static pages like `user/1`, `user/2`, and `user/3`.

Syntax:

export async function getStaticPaths() {
      // your code here
      return {
        paths,
        fallback,
      }
}

Return type: Object with two parameters-paths, fallBack

  • paths is an array that contains the value of the dynamic parameter of the pre-generated static pages.
  • fallBack is a variable that controls the action when the user is trying to access a page whose dynamic parameter is not listed in the paths array.
    • The fallBack property has two values: 
      • false: The `false` value is the default value of the fallback property. If the request of the user is not listed in the paths array the NextJS will return a 404 page as the result.
      • true: The `true` value tells the NextJS to generate the static version for the request of the user on the fly.

Steps to create a NextJS application:

Step-1: create a next app and name it using the following command:

npx create-next-app example

Step-2: create a User folder in the pages folder in the app-hierarchy

pages/User

Step-3: create a dynamic page in the User folder

pages/User/[userId].js

Project Structure:

App-Hierarchy

Example 1:

[userId].js file:

Javascript




import { useRouter } from 'next/router';
  
// useRouter access the current route
//  and its dynamic Parameters
function User(props) {
    const router = useRouter();
    const { userId } = router.query; 
    // Destructuring the query of the
    // router to extract userId
  
    return (
        <div>
            <h1>Geek {userId}</h1>
            <p>Geek {userId} is Viewing...</p>
        </div>
    );
}
export async function getStaticPaths() {
    return {
        paths: [
            { params: { userId: '1' } },
            { params: { userId: '2' } },
            { params: { userId: '3' } },
        ],
        fallback: false 
        // If the page with the userId is 
        // not found, returns 404 page
    };
}
export async function getStaticProps({ params }) {
    const { userId } = params;
    const User = {
        id: userId,
        title: `Geek ${userId}`,
        content: `Geek ${userId} is Viewing...`
    };
  
    return {
        props: {
            User
        }
    };
}
  
export default User;


Explanation:

  • The useRouter hook is used to access the current router and its dynamic parameters. In this example, the useRouter is used to extract the userId from the current router by destruction.
  • The getStaticPaths() function is used to create the static pages for all possible values of the dynamic parameters. In this example, we are passing the userId’s (1, 2, 3) into the params.

Output:

output

Example 2: use of getStaticPaths() with API

[Id].js

Javascript




export async function getStaticPaths() {
    const result = await fetch('https://.../MAjhqg/data');
    const users = await result.json();
    const paths = users.map((user) => ({
        params: { id: user.id.toString() },
    }));
    return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
    const result = await fetch(`https://.../MAjhqg/data/${params.id}`);
    const user = await result.json();
    return { props: { user } };
}
export default function UserPage({ user }) {
    return (
        <div>
  
            <h1 style={{ paddingLeft: 40 }}>Name: {user.name}</h1>
            <p style={{ paddingLeft: 40 }}>Id: {user.id}</p>
        </div>
    );
}


Explanation:

  • In this example, getStaticPaths() fetches a list of all userIds from the API and generates an array of objects with the params key for each id.
  •  getStaticProps() fetches the user data for the given id and returns it as props to the page component. Finally, the page component displays the product data.

Output:

output

Steps to build and execute the above examples:

npm run build

Steps to execute the code:

  • use the command:
npm run dev
  • open your browser and go through the following links to see the output
    • `http://localhost:3000/User/1`
    • `http://localhost:3000/User/2`
    • `http://localhost:3000/User/3`
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