원본: https://nextjs.org/docs/basic-features/data-fetching/get-static-paths
어떤 페이지가 동적 루트를 가지고 있고 getStaticProps를 사용한다면 정적으로 생성될 경로들의 목록을 정의해야 한다.
동적 루트를 사용하는 페이지에서 getStaticPaths라는 함수를 export하면 Next.js는 이 함수에 의해 지정된 모든 경로를 정적으로 미리 렌더링 한다.
여기에서 getStaticPaths와 함께 사용할 수 있는 파라미터와 props를 확인할 수 있다.
// pages/posts/[id].js
// Generates `/posts/1` and `/posts/2`
export async function getStaticPaths() {
return {
paths: [{ params: { id: '1' } }, { params: { id: '2' } }],
fallback: false, // can also be true or 'blocking'
}
}
// `getStaticPaths` requires using `getStaticProps`
export async function getStaticProps(context) {
return {
// Passed to the page component as props
props: { post: {} },
}
}
export default function Post({ post }) {
// Render post...
}
동적 경로를 사용하고 다음과 같은 페이지들을 사전 렌더링 하는 경우에 getStaticPaths를 사용해야 한다.
getStaticPaths는 production 빌드 시에만 실행되고, 런타임에는 실행되지 않는다.
next dev를 사용하여 개발하는 중에는 getStaticPaths가 모든 요청마다 실행된다.
getStaticPaths를 사용하면 빌드 중에 페이지 생성 실패 후 fallback를 생성하는 것 대신 페이지를 생성할지를 제어할 수 있다. 빌드 중에 더 많은 페이지를 생성하는 것은 더 느린 빌드를 초래한다.
paths를 빈 배열로 반환하면 요청 시 모든 페이지 생성을 연기할 수 있다. 이렇게 하면 Next.js 어플리케이션을 여러 환경에 배포할 때 특히 유용할 수 있다.
// pages/posts/[id].js
export async function getStaticPaths() {
// When this is true (in preview environments) don't
// prerender any static pages
// (faster builds, but slower initial page load)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to prerender based on posts
// In production environments, prerender all pages
// (slower builds, but faster initial page load)
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// { fallback: false } means other routes should 404
return { paths, fallback: false }
}