Next.js getStaticPaths() Function (original) (raw)

Last Updated : 26 Jul, 2024

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

**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 ``

//[userId].js file:

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:

**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 (

        <h1 style={{ paddingLeft: 40 }}>Name: {user.name}</h1>
        <p style={{ paddingLeft: 40 }}>Id: {user.id}</p>
    </div>
);

}

``

**Explanation:

**Output:

**Steps to build and execute the above examples:

npm run build

**Steps to execute the code:

npm run dev