Values Returned by getStaticPaths
The object returned by the getStaticPaths function must have the following properties:
Paths
The paths that will be pre-rendered is determined by the pathways key. Consider the following scenario: you have a page named pages/posts/[id].js that uses Dynamic Routes. If you export getStaticPaths from this page, the paths will look like this:
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: ...
}
Then, using the page component in pages/posts/[id].js, Next.js will statically generate /posts/1 and /posts/2 during the next build.
Each params object's value must match the parameters in the page name:
- If the page's name is pages/posts/[postId]/[commentId], postId and commentId should be included in the params.
- If the page name includes catch-all routes such as pages/[...slug], the slug parameter should be included in the params (an array). If this array contains ['hello', 'world,'], Next.js will construct the page statically at /hello/world.
- If the page includes an optional catch-all route, render it null, [], undefined, or false. If you specify slug: false for pages/[[...slug]], Next.js will construct the page / statically.
fallback: false
Any paths not returned by getStaticPaths will result in a 404 page if fallback is false.
If fallback: false were returned by getStaticPaths, Next.js would only build the paths produced by getStaticPaths when the next build is run. This option is beneficial if you need to construct a few pathways or new page data isn't added frequently. If you discover that you need to add more routes and fallback: false, you'll need to rerun the next build to produce the new paths.
The next example, pages/posts/[id].js, pre-renders one blog post each page. The getStaticPaths will retrieve a list of blog articles from a CMS and return it. Then, using getStaticProps, it gets the post data from a CMS for each page.
// pages/posts/[id].js
function Post({ post }) {
// Render post...
}
// The following function is called at build time
export async function getStaticPaths() {
// To obtain posts, use an external API endpoint.
const res = await fetch('https://.../posts')
const posts = await res.json()
// Obtain the pathways we wish to render ahead of time based on postings.
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// Only these pathways will be pre-rendered at build time.
// Other routes should be 404 if fallback: false is set.
return { paths, fallback: false }
}
// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// params.id is 1 if the route is like /posts/1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Props are used to pass post data to the page.
return { props: { post } }
}
export default Post
fallback: true
If fallback is true, getStaticProps behaves differently in the following ways:
- GetStaticProps will render the routes supplied by getStaticPaths to HTML at build time.
- A 404 page will not be provided for paths that were not generated at build time. Instead, on the first request to such a path, Next.js will offer a "fallback" version of the page.
- Next.js will produce the requested path HTML and JSON statically in the background. This includes getting static properties with getStaticProps.
- The browser receives the JSON for the produced path after it's finished. This will be utilised to render the page with the appropriate properties automatically. From the user's perspective, the page will be switched from the fallback to the entire page.
When utilizing next export, fallback: true is not supported.
fallback: blocking
If the fallback is 'blocking,' new paths not returned by getStaticPaths will wait for the HTML to be created, similar to SSR (thus the blocking), before being cached for future requests.
Fallback Pages
In the "fallback" version of a page:
- The props on the "fallback" version of a page will be empty.
- You can use the router to see if the fallback is being rendered. The value of isFallback will be true.
The following example demonstrates how to use isFallback:
// pages/posts/[id].js
import { useRouter } from 'next/router'
function Post({ post }) {
const router = useRouter()
// If the page has not yet been produced, this will be displayed until getStaticProps() has completed.
if (router.isFallback) {
return <div>Loading...</div>
}
// Render post...
}
// The following function is called during build time
export async function getStaticPaths() {
return {
// At build time, only `/posts/1` and `/posts/2` are generated
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
// Enable statically generating additional pages
// For example: `/posts/3`
fallback: true,
}
}
// gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// params.id is 1 if the route is like /posts/1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()
// Props are used to pass post data to the page.
return {
props: { post },
// If a request comes in, re-generate the post at least once every second.
revalidate: 1,
}
}
export default Post
When should we use getStaticPaths()?
We use getStaticPaths if we're statically pre-rendering pages that use dynamic routes.
- The data originates from a CMS that doesn't have a head.
- The information is taken from a database.
- The data is taken from the filesystem.
-
The data can be cached openly (not user-specific).
NOTE:
The only way to export getStaticPaths is from a page. It is not possible to export it from non-page files.
It's essential to note that you must use export getStaticPaths as an independent function; adding getStaticPaths as a page component attribute will not work.
When does getStaticPaths() run?
On the server, getStaticPaths is only called at build time. GetStaticPaths can also be executed on-demand in the background if you're using Incremental Static Regeneration, but only on the server-side.
getStaticPaths will be called on every request in development (next dev).
Check out this problem - Root To Leaf Path
FAQs
-
What is getStaticPaths?
The getStaticPaths() function tells the Next. js to render the pages defined in paths. This function always returns the object.
-
Why do I need getStaticPaths?
You should use getStaticPaths if you're statically pre-rendering pages that use dynamic routes. If a page has dynamic routes (documentation) and uses getStaticProps, it needs to define a list of paths that have to be rendered.
-
Why is the next JS used?
Next.js is a React Framework for front-end development that allows us to use features like static website generation and server-side rendering in React-based web apps.
Key Takeaways
Today, we learned the getStaticPaths() method in Next.js. It is used for rendering dynamic web pages. We also learned its applications and use cases.
For more articles related to Next.js, please head to the following links:
Building First App in Next.js.
Happy learning!