getServerSideProps
페이지에서 getServerSideProps를 사용하면 해당 함수에서 반환된 데이터를 이용해 페이지를 미리 렌더링한다.
export async function getServerSideProps(context) {
return {
props: {},
}
}
getServerSideProps는 언제 실행될까?
getServerSideProps는 브라우저에서 실행되지 않고 서버에서만 실행된다.
페이지에서 getServerSideProps를 사용하는 경우
- 해당 페이지를 직접 요청하면 getServerSideProps가 실행되고 반환된 데이터로 사전 렌더링된다.
- 브라우저에서 next/link 또는 next/router를 통해 해당 페이지로 페이지 전환을 하게되면 Next.js는 getServerSideProps를 실행하는 서버에 API 요청을 보낸다.
getServerSideProps는 JSON을 반환하며, Next.js가 자동으로 처리하기 때문에 추가 작업은 필요 없다. getServerSideProps는 pages 폴더 내에 있는 페이지 안에서만 사용할 수 있으며, 페이지의 component 구성 요소가 아닌 component 함수 밖에 단독으로 작성해야한다.
getServerSideProps는 언제 사용해야 할까?
요청시 데이터를 가져와야하는 경우에만 선택적으로 getServerSideProps를 사용하는 것이 좋다. getServerSideProps를 사용하는 페이지는 요청시 서버측에서 렌더링되며 캐시 제어 헤더가 구성된 경우에만 캐시된다.
getServerSideProps or API Routes
서버에서 데이터를 가져올 때 getServerSideProps에서 API(pages/api 폴더 안에 있는 api를 뜻하는 듯?)를 호출하고 싶을 수 있다. 이렇게 하면 추가 요청이 발생하기때문에 불필요하고 비효율적이며 성능이 저하된다. 이렇게 하는 것보다는 getServerSideProps에서 직접 데이터를 호출하는 것이 좋다.
Fetching data on the client side
페이지에 자주 업데이트되는 데이터가 있고 데이터를 미리 렌더링할 필요가 없는 경우 클라이언트 측에서 데이터를 가져올 수 있다.
- 데이터가 없는 페이지를 표시한 후 클라이언트 측에서 데이터를 가져와서 준비되면 표시한다.
이러한 방식은 SEO가 필요없는 페이지에 적합하다.
예시
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
Caching with Server-Side Rendering (SSR)
getServerSideProps 내부의 캐싱 헤더를 사용해 동적 응답을 캐싱할 수 있다.
// This value is considered fresh for ten seconds (s-maxage=10).
// If a request is repeated within the next 10 seconds, the previously
// cached value will still be fresh. If the request is repeated before 59 seconds,
// the cached value will be stale but still render (stale-while-revalidate=59).
//
// In the background, a revalidation request will be made to populate the cache
// with a fresh value. If you refresh the page, you will see the new value.
export async function getServerSideProps({ req, res }) {
res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
)
return {
props: {},
}
}
Does getServerSideProps render an error page
getServerSideProps 내부에서 오류가 발생하면 pages/500.js 파일이 표시된다. 개발 중에는 이 파일 대신 개발 오버레이가 표시된다.
'Next.js' 카테고리의 다른 글
Data Fetching - getStaticProps (0) | 2022.12.29 |
---|---|
Data Fetching - getStaticPaths (0) | 2022.12.27 |
Pages (0) | 2022.12.23 |
Next.js 시작하기 (0) | 2022.12.23 |
댓글