구어체로 설명하는 다이어리

getServerSideProps란? 본문

스터디/Next.js

getServerSideProps란?

씨씨상 2024. 9. 22. 17:31

 

 

getServerSideProps는 Next.js에서 SSR (Server Side Rendering) 하기 위한 방법입니다.

서버 단에서 데이터를 받아와 클라이언트 페이지에 렌더링하는데요.

이 함수는 페이지를 요청할 때마다 호출되고, HTML을 서버 단에서 먼저 생성하여 클라이언트에 전달합니다.

미리 페이지를 생성한다는 점에서 역시 SEO에 좋은 선택입니다.

 

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next';

type Repo = {
  name: string;
  stargazers_count: number;
};

export const getServerSideProps = (async () => {
  // Fetch data from external API
  const res = await fetch('https://api.github.com/repos/vercel/next.js');
  const repo: Repo = await res.json();
  // Pass data to the page via props
  return { props: { repo } };
}) satisfies GetServerSideProps<{ repo: Repo }>;

export default function Page({ repo }: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <main>
      <p>{repo.stargazers_count}</p>
    </main>
  );
}

 

코드를 보면 getServerSideProps로 데이터를 fetch 한 후 그 결과를 Page props (repo)로 전달해주고 있죠.

이처럼 SEO에 중요한 페이지를 서버로부터 미리 값을 가져와 보여주길 원하거나,

페이지 접근 시마다 최신 데이터를 보여주고 싶을 때 주로 사용합니다.

props로 전달하면 getStaticProps와 동일하게 초기 HTML 일부로 볼 수 있으니 민감한 정보는 전달하지 않도록 합니다.

 

 

 

 

 

참고자료

참고자료1

 

Data Fetching: getServerSideProps | Next.js

Fetch data on each request with `getServerSideProps`.

nextjs.org

참고자료2

'스터디 > Next.js' 카테고리의 다른 글

getStaticProps와 getStaticPaths란?  (0) 2024.09.14