페이지에서 getStaticProps 함수를 내보내면 반환된 props를 사용해 빌드시 페이지를 미리 렌더링한다.
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
When should I use getStaticProps?
- 페이지를 렌더링하는데 필요한 데이터가 사용자 요청보다 앞서 빌드되어야할 때
- The data comes from a headless CMS
- 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
- The data can be publicly cached (not user-specific). This condition can be bypassed in certain specific situation by using a Middleware to rewrite the path.
When does getStaticProps run
getStaticProps는 항상 서버에서 실행된다.
- getStaticProps는 next build시 실행된다.
- getStaticProps는 fallback: true일 때 background에서 실행된다.
- getStaticProps는 fallback: blocking일 때 초기 렌더링 전에 실행된다.
- getStaticProps는 revalidate를 사용할 때 background에서 실행된다.
- getStaticProps는 revalidate()를 사용할 때 요청 즉시 background에서 실행된다.
getStaticProps는 ISR과 같이 사용하면 페이지가 검증되는 동안 백그라운드에서 실행되며, 새로운 페이지가 제공된다.
getStaticProps는 정적 HTML을 생성하므로 들어오는 요청에 액세스 할 수 없다. 이러한 경우 getStaticProps 외에 미들웨어를 사용하는 것이 좋다.
Using getStaticProps to fetch data from a CMS
블로그 게시물 목록을 가져오는 방법 예시
// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
return (
<ul>
{posts.map((post) => (
<li>{post.title}</li>
))}
</ul>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../posts')
const posts = await res.json()
// By returning { props: { posts } }, the Blog component
// will receive `posts` as a prop at build time
return {
props: {
posts,
},
}
}
export default Blog
Write server-side code directly
getStaticProps는 서버측에서만 실행되기 때문에 직접 데이터베이스 쿼리를 작성할 수 있다. 즉, getStaticProps에서 api route를 가져오는 대신(/pages/api 폴더 안의 api를 말하는 듯?) getStaticProps에서 직접 서버 측 코드를 작성할 수 있다.
api route가 getStaticProps에서 직접 호출시 추가 호출이 발생하여 성능이 저하된다. 이런 방법 대신에 lib/ 폴더를 사용해 데이터를 가져오는 로직을 공유할 수 있으며, 해당 로직을 getStaticProps에서 사용할 수 있다.
// lib/load-posts.js
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
export async function loadPosts() {
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts/')
const data = await res.json()
return data
}
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
또는 api route를 사용하여 데이터를 가져오지 않는 경우 getStaticProps에서 직접 데이터를 가져올 수 있다.
Statically generates both HTML and JSON
getStaticProps가 있는 페이지가 빌드시 미리 렌더링되면 HTML 파일 외에도 getStaticProps 실행 결과를 포함하는 JSON 파일을 생성한다. JSON 파일은 next/link 또는 next/router를 통한 클라이언트 측 라우팅에 사용된다. getStaticProps를 사용해 미리 렌더링된 페이지로 이동하면 이 JSON 파일을 가져와 페이지의 props으로 사용한다. 이것은 내보낸 JSON만 사용되므로 클라이언트측 페이지 전환이 getStaticProps를 호출하지 않는 것을 의미한다.
ISR을 사용하는 경우 클라이언트 측 탐색에 필요한 JSON을 생성하기 위해 getStaticProps가 백그라운드에서 실행되지만 사용자 성능에 영향을 미치지는 않는다.
Where can I use getStaticProps
getStaticProps는 페이지에서만 내보낼 수 있다. 이러한 이유 중 하나는 페이지가 렌더링되기 전에 React에 필요한 모든 데이터가 있어야 하기 때문이다.
또한 getStaticProps는 페이지의 구성 요소가 아닌 독립적인 함수로 실행해야한다.
Runs on every request in development
개발 모드시 getStaticProps는 모든 요청에서 호출된다.
Preview Mode
정적 생성을 일시적으로 우회하고 미리보기 모드를 사용하여 빌드 시간 대신 요청 시간에 페이지를 렌더링할 수 있다.
'Next.js' 카테고리의 다른 글
Data Fetching - getStaticPaths (0) | 2022.12.27 |
---|---|
Data Fetching - getServerSideProps (0) | 2022.12.26 |
Pages (0) | 2022.12.23 |
Next.js 시작하기 (0) | 2022.12.23 |
댓글