nextjs의 서버사이드 렌더링에서 data를 fetch하는 방법을 알아보자
페이지에서 getServerSideProps
함수를 리턴하는 경우에는 해당 함수가 리턴하는 props
를 통하여 컴포넌트가 렌더링되기 이전에 pre-rendering
한다.
page
에서만 내보낼수있다 (component X)pages/500.js
가 뜬다function Page({ data }) {
// Render data...
}
// This gets called on every request
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://.../data`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Page
내부의 캐싱헤더 (Cache-Control)를 사용하여 dynamic responses를 캐싱할수있다(?)
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
정적 생성 방식이며, Next.js에서 권고하는 방식이다
getServerSideProps
보다 성능적인 이점이 있다.export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
page
에 dynamic routes(동적 경로)를 사용하는 페이지에서 사용된다.
해당함수를 export시키면 모든 경로를 미리 정적으로 렌더링한다.
paths
, fallback
이 있다fallback
은 (true | false | "blocking") 3가지 값이 있는데getStaticPaths
에서 리턴하지 않는 페이지에 접속시 fallback
페이지나 로딩
페이지가 없다.true와 "blocking" 값은 모두 fallback을 일으키는점에서 비슷하지만, true는 새로운 path에 대해 요청이 왔을때 build시 정적 사이트를 만드는 과정에 fallback버전의 임시페이지가 보여졌다가, 정적생성된 페이지를 보여준다.그리고 build파일에 추가 파일을 남긴다.
"blocking"은 true와 동일하지만 fallback버전의 임시페이지를 보여주지않고 build파일에 파일을 추가하지않는다.
// pages/posts/[id].tsx라는 동적경로 페이지
// "/posts/1"과 "/posts/2"를 생성한다.
export async function getStaticPaths(){
return {
paths:[],
fallback: false,
}
}
export async function getStaticProps(contex){
return {
props : {}
}
}
getServerSideProps
는 page가 리렌더링 될때마다 요청되므로 동적인 데이터를 다루는 페이지에서 사용getStaticProps
는 build시에만 요청되므로 (fallback조건도 있지만) 정적인 데이터를 다룰때 사용함. 성능적인 이점이 있음getStaticPaths
는 Dynamic route에서 사용. ISR
개념