개발/자바스크립트

[NextJS] getSererSideProps

대왕판다 2022. 3. 24. 12:53

넥스트JS의 가장 큰 장점인 SSR을 살리기 위해서는 getServerSideProps를 export해주어야한다.

export default function Home({ results }) {
  // 데이터 렌더링!
}


export async function getServerSideProps() {
  const { results } = await (
    await fetch("http://localhost:3000/api/movies")
  ).json();
  return {
    props: {
      results,
    },
  };
}

이때 넥스트js는 반환된 데이터를 사용해 req에서 페이지를 pre-render하게 된다.

요 getServerSideProps는 서버측에서만 실행되며 클라이언트에서는 X

사용자에게 api에서 fetch하는 동안 듬성듬성한 페이지, 혹은 로딩 페이지를 보여주지 않는 장점 O

 

그러나 SEO와 관련 없는 페이지거나, 데이터 업데이트가 잦은 페이지라면,

클라이언트에서 렌더링 하는것도 고려해야한다!

 

 

참고)

https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

노마드코더 슈가님(https://github.com/GitHubGW)

 

Data Fetching: getServerSideProps | Next.js

Fetch data on each request with `getServerSideProps`.

nextjs.org