[NextJS] Server Side Rendering

상현·2023년 12월 20일
2

NextJS

목록 보기
4/6
post-thumbnail

SSR은 동적 렌더링 이라고도 한다.

SSR을 사용하는 페이지는 클라이언트로 요청이 들어올 때마다 HTML을 생성한다. NextJS에서 SSR을 사용하기 위해서는 getServerSideProps 라는 비동기 함수를 호출하고 export 하면 된다.

getServerSideProps

getServerSidePropsgetStaticProps와는 다르게 먼저 클라이언트에서 요청이 들어오면 페이지를 생성 후 보여준다.
기본 기능은 getStaticProps와 같으며, 둘 중 하나만 선택해서 사용해야 한다.
추가로 return 하는 항목에는 revalidate 가 있으면 안된다. 왜냐하면 getServerSideProps는 요청이 들어올 때마다 항상 실행되기 때문이다.

언제 사용할까?

사용자에 따라 다른 정보를 보여주는 페이지나, 실시간 차트 등 매 요청마다 동적인 데이터를 필요로 하는 경우에 사용할 수 있다.

context

getStaticProps 와는 다르게 context 매개변수 안에 params 말고도 reqres 에도 접근할 수 있다.

따라서 다음과 같이 페이지에 응답을 조작하여 보낼 수 있다.

export async function getServerSideProps({ req, res }) {
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=10, stale-while-revalidate=59'
  )
 
  return {
    props: {},
  }
}```


1개의 댓글

comment-user-thumbnail
2023년 12월 22일

Gynbet https://gynbt.com/app/ offers a wide range of betting options to cater to the diverse preferences of its users. Whether you are a fan of traditional sports betting or you prefer the thrill of live betting, Gynbet has got you covered.

답글 달기