Next.js

Data Fetching - getStaticPaths

NANDEV 2022. 12. 27. 11:50

페이지에 동적 경로가 있고 getStaticPaths를 사용할 경우 생성할 경로 목록을 정의해야한다. 동적 경로를 사용하는 페이지에서 getStaticPaths 함수를 내보내면 Next.js는 지정한 모든 경로를 정적으로 사전 렌더링한다.

// 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...
}

 

When should I use getStaticPaths?

동적 경로를 사용하는 페이지를 정적으로 사전 렌더링하는 경우 사용해야하며, 아래의 경우 사용할 수 있다.

  • The data comes from a headless CMS
  • The data comes from a database
  • The data comes from the filesystem
  • The data can be publicly cached (not user-specific)
  • The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance

 

When does getStaticPaths run

getStaticPaths는 빌드시에 실행된다.

 

How does getStaticProps run with regards to getStaticPaths

  • getStaticProps는 next build가 실행되는 동안 빌드 중에 반환된 모든 경로에 대해 실행된다.
  • getStaticProps는 fallback: true를 사용하면 background에서 실행된다.
  • getStaticProps는 fallback: blocking을 사용하면 초기 렌더링 전에 호출된다.

 

Where can I use getStaticPaths

  • getStaticPaths는 getStaticProps와 같이 사용해야한다.
  • getStaticPaths와 getServerSideProps를 같이 사용할 수 없다.
  • getStaticPaths는 getStaticProps를 사용하는 동적 경로에서 내보낼 수 있다.
  • getStaticPaths는 페이지가 아닌 파일에서 사용할 수 없다.
  • getStaticPaths는 페이지의 구성 요소가 아닌 독립적인 함수로 작성해야한다.

 

Runs on every request in development

getStaticPaths는 개발 모드시 모든 요청에서 호출된다.

 

Generating paths on-demand

getStaticPaths는 fallback이 있는 on-demand 대신 빌드 중에 생성되는 페이지를 제어할 수 있다. 빌드 중에 더 많은 페이지를 생성하면 빌드 속도가 느려진다.

경로에 빈 배열을 반환해서 요청하면 모든 페이지의 생성을 연기할 수 있다. 이렇게하면 Next.js 어플리케이션을 여러 환경에 배포할 때 유용하다. 예를 들어 미리 보기를 위해 on-demand(쉽게 요청시에 즉시) 모든 페이지를 생성하여 더 빠르게 빌드할 수 있다. 이것은 수백/수천개의 정적 페이지가 있는 사이트에 유용하다.

// 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 }
}

 

반응형