[Next.js] Data Fetching 정리
https://nextjs.org/docs/basic-features/data-fetching/overview
Data Fetching: Overview | Next.js
Next.js allows you to fetch data in multiple ways, with pre-rendering, server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.
nextjs.org
Next.js의 공식 문서를 토대로 Next.js의 pre-rendering 과정에서의 SSR(Server-side rendering)과 SSG(Static-state generation) 방식에 대해서 살펴보려고 합니다. 더 나아가 ISG(Incremental Static Regeneration)에 대해서도 살펴볼 예정입니다.
getServerSideProps
SSR을 구현할 때 사용하는 함수로 아래와 같이 구현할 수 있습니다.
export async function getServerSideProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
getServerSideProps를 이용하면 페이지를 요청할 때마다 pre-rendering이 실행됩니다.
요청 시에 data가 fetch되어야 하는 경우에 이 함수를 사용해야 합니다.
getStaticPaths
getStaticPaths는 dynamic routes를 이용해 구현될 주소들을 미리 정의할 때 사용하며 아래와 같이 작성해주면 됩니다.
export async function getStaticPaths() {
return {
paths: [
{ params: { ... } }
],
fallback: true // false or 'blocking'
};
}
getStaticPaths는 아래서 살펴볼 getStaticProps와 함께 쓰여야 하고, getServerSideProps와는 함께 쓰일 수 없습니다.
여기서 fallback 옵션은 false, true, blocking으로 되어 있는데 정의되지 않은 주소를 요청할 때 404 페이지를 반환할지 말지를 결정합니다.
false인 경우 404를 반환하고, true, blocking일 경우 반환하지 않습니다.
blocking은 완전히 빌드가 끝난 이후에 사용자에게 페이지를 표시해주고, true는 그냥 페이지를 표시해주는데 아래와 같이 빌드 중인지 여부를 판단해서 다뤄줄 수 있습니다.
const router = useRouter()
// If the page is not yet generated, this will be displayed
// initially until getStaticProps() finishes running
if (router.isFallback) {
return <div>Loading...</div>
}
getStaticProps
getStaticProps는 SSG를 위해 사용되는 친구로 아래와 같이 구현할 수 있습니다.
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}
getStaticProps는 빌드 할 때 한 번 호출되고 이후에 수정이 불가합니다.
따라서 빌드 이후 바뀌지 않는 내용이 있는 경우에 사용하는 것이 좋습니다.
getServerSideProps보다 성능적인 이점을 가진다는 특징이 있습니다.
ISG(Incremental Static Regeneration)
ISG는 SSG에서 한 발자국 더 나아가 빌드 이후에도 수정사항을 반영할 수 있게 합니다.getStaticProps
의 return 값에 revalidate
를 아래와 같이 추가해주면 됩니다.
export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 10 seconds
revalidate: 10, // In seconds
}
}
revalidate는 regeneration을 트리거하는 기준 시간입니다.
예를 들어 현재 렌더링되어 있는 페이지 A가 있다고 하고 revalidate가 10초라고 합시다.
오후 1시 정각에 사용자 1이 페이지 A에 접근하면 페이지 regeneration이 trigger됩니다. 이 때 사용자 1은 페이지 A를 바라보게 됩니다.
오후 1시 0분 5초에 사용자 2가 페이지 A에 접근하는 경우 사용자2는 여전히 기존 페이지인 페이지 A를 보게되는데 revalidate 시간인 10초 이내에 접근했기 때문입니다.
오후 1시 0분 10초 이후에서는 rebuild된 페이지인 페이지 A'가 나오게 됩니다.
이 이후부터는 새롭게 생성된 페이지 A'가 서브되고, 오후 1시 1분 0초에 사용자 3이 페이지 A에 접근하게 된다면 사용자 3은 페이지 A'를 보게 됩니다.
Static Reactions Demo next.js 데모 사이트인데 revalidate=1인 ISG를 이용한 사이트입니다.
개념 이해하실 떄 참고하시면 좋습니다
참고
https://mytutorials.tistory.com/317
Next.js Incremental Static Regeneration 알게 된것! Revalidate = timeout
// next.js의 예제 코드 function Blog({ posts }) { return ( {posts.map((post) => ( {post.title} ))} ) } // This function gets called at build time on server-side. // It may be called again, on a serv..
mytutorials.tistory.com