Next JS getStaticPaths function
getStaticPaths
is a function used in Next.js for Dynamic Static Site Generation (SSG). It is particularly useful for generating static pages for dynamic routes based on external data, such as an API or database. When you have a page that depends on dynamic parameters (like blog post IDs, product slugs, etc.), getStaticPaths
enables you to specify which paths should be pre-rendered at build time.
Key Features of getStaticPaths
Dynamic Routes: It is used in conjunction with dynamic routes, which are defined by square brackets in the file name (e.g.,
[id].js
).Paths Generation:
getStaticPaths
allows you to define an array of paths that will be statically generated. Each path corresponds to a specific instance of a page.Fallback Options: You can configure fallback behavior to handle paths that were not pre-rendered at build time. This allows for greater flexibility in how dynamic content is served.
Basic Usage
Here's how to use getStaticPaths
in a Next.js page component:
Step 1: Create a Dynamic Route
Create a dynamic route file in the pages
directory:
// pages/posts/[id].js
import { useRouter } from 'next/router';
export default function Post({ post }) {
const router = useRouter();
// Show a loading state while the page is being generated
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{post.title}</h1>
<p>{post.content}</p>
</div>
);
}
// Step 2: Use getStaticPaths to define the paths
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
// Generate paths for the first 10 posts
const paths = posts.slice(0, 10).map(post => ({
params: { id: post.id.toString() }, // Ensure the id is a string
}));
return {
paths,
fallback: true, // true, false, or 'blocking'
};
}
// Step 3: Use getStaticProps to fetch data for each page
export async function getStaticProps({ params }) {
const res = await fetch(`https://api.example.com/posts/${params.id}`);
const post = await res.json();
return {
props: { post },
};
}
Explanation of the Code
Dynamic Route: The file
pages/posts/[id].js
defines a dynamic route for blog posts whereid
is a variable parameter.Page Component: The
Post
component displays the content of the fetched post. If the route is being generated on the fly (i.e., fallback mode is active), it shows a loading state.getStaticPaths Function:
- This function is called at build time to generate the static paths.
- It fetches data (in this case, a list of posts) and maps through it to create an array of path objects. Each object has a
params
key with anid
corresponding to the post. - The returned object contains:
paths
: An array of paths to pre-render.fallback
: A boolean or string that controls the fallback behavior (explained below).
getStaticProps Function:
- This function is called for each path returned by
getStaticPaths
to fetch the specific data for that post. - It receives
params
, allowing you to fetch data based on the dynamicid
.
- This function is called for each path returned by
Fallback Options
The fallback
property in getStaticPaths
determines how Next.js handles paths not returned by getStaticPaths
:
false
:- Next.js will return a 404 page for any paths that are not returned from
getStaticPaths
. Only the specified paths will be pre-rendered.
- Next.js will return a 404 page for any paths that are not returned from
true
:- Next.js will serve a static shell for paths that are not pre-rendered, while it generates the page on the server. The user will see a loading state until the new page is fully rendered.
'blocking'
:- Similar to
true
, but it will wait to render the new page before sending a response to the client. The user will not see a loading state, but they may experience a slightly longer wait for the page to load.
- Similar to
Example with Fallback
When using fallback: true
, your page will look something like this:
if (router.isFallback) {
return <div>Loading...</div>; // Show a loading state while generating the page
}
Use Cases for getStaticPaths
Blog Posts: Generate static pages for a list of blog posts, where each post's content is fetched based on its ID.
Product Pages: Create individual product detail pages dynamically based on a product slug or ID.
User Profiles: Build user profile pages using user IDs or usernames as dynamic routes.
Summary
getStaticPaths
is a crucial function in Next.js for defining dynamic routes and specifying which paths should be pre-rendered at build time. By using it alongside getStaticProps
, you can efficiently generate static pages for dynamic content while also handling fallback scenarios to ensure a seamless user experience. This makes it a powerful tool for building applications with content that changes frequently but benefits from static optimization.