본문 바로가기

개발 공부/React

getStaticProps, getStaticPaths, getServerSideProps

Next.js는 정적 사이트 생성(Static Generation)과 서버 사이드 렌더링(Server-side Rendering)을 모두 지원하는 하이브리드 프레임워크입니다.

이 두 방식을 기반으로, Next.js는 데이터를 불러오기 위한 세 가지 주요 함수인 getStaticProps, getStaticPaths, getServerSideProps를 제공합니다.

 

getStaticProps - 정적 생성용 데이터 패칭 함수

getStaticProps정적 생성(Static Generation)을 위해 데이터를 빌드 시점에 가져오는 함수입니다.

미리 데이터를 불러와 HTML 파일을 생성하고, 사용자는 CDN에 캐시된 페이지를 빠르게 받아볼 수 있습니다.

사용 시점

  • 데이터가 빌드 시점에 결정되어도 되는 경우
  • 자주 변경되지 않는 콘텐츠 (예: 블로그 포스트, 제품 소개 페이지 등)

예시

// pages/posts.tsx
import { GetStaticProps } from 'next';

export const getStaticProps: GetStaticProps = async () => {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  return {
    props: { posts },
    revalidate: 60, // ISR (Incremental Static Regeneration)
  };
};

export default function Posts({ posts }) {
  return (
    <ul>
      {posts.map(post => <li key={post.id}>{post.title}</li>)}
    </ul>
  );
}

 

ISR: Incremental Static Regeneration

  • revalidate: 60을 설정하면, 이 페이지는 60초마다 백그라운드에서 다시 생성됩니다.
  • 매우 큰 페이지라도 유저가 느끼기엔 정적 페이지처럼 빠르고, 실제 데이터는 최신으로 유지됩니다.
 
 

getStaticPaths - 동적 경로 정적 생성에 필수

getStaticPathsgetStaticProps와 함께 사용됩니다.

동적 라우트(예: /posts/[id])를 사용할 때, 어떤 경로들을 정적으로 미리 생성할지 정의합니다.

사용 시점

  • 블로그, 제품 상세 페이지 등 동적 경로가 필요한 정적 페이지 생성
  • URL이 동적으로 구성되지만, 콘텐츠는 자주 바뀌지 않는 경우

예시

// pages/posts/[id].tsx
import { GetStaticPaths, GetStaticProps } from 'next';

export const getStaticPaths: GetStaticPaths = async () => {
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  const paths = posts.map(post => ({
    params: { id: post.id.toString() },
  }));

  return {
    paths,
    fallback: 'blocking', // true | false | 'blocking'
  };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();

  return {
    props: { post },
    revalidate: 10,
  };
};

⚠️ fallback 옵션

  • false: paths에 정의된 것만 빌드되고, 없는 경로는 404
  • true: 없는 경로도 클라이언트가 접속하면 백그라운드에서 페이지 생성
  • 'blocking': 없는 경로에 접근 시 서버에서 페이지를 먼저 생성하고 보여줌
 
 

getServerSideProps - 요청 시마다 서버에서 실행

getServerSideProps모든 요청마다 서버에서 실행되는 함수입니다.

페이지가 요청될 때마다 최신 데이터를 받아와 렌더링합니다.

사용 시점

  • 항상 최신 데이터가 필요한 경우
  • 로그인, 인증 등 세션 기반의 동적 콘텐츠
  • SEO가 중요한 실시간 데이터 페이지 (예: 대시보드, 관리자 화면)

예시

// pages/profile.tsx
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const res = await fetch('https://api.example.com/user', {
    headers: {
      Cookie: context.req.headers.cookie || '',
    },
  });
  const user = await res.json();

  return {
    props: { user },
  };
};

세션/토큰 활용 가능

  • context.req, context.res를 통해 쿠키, 인증 헤더 접근 가능
  • 로그인 체크, 권한 처리에 용이

비교

함수 실행 시점 캐싱 사용 사례 특징
getStaticProps 빌드 타임 O 블로그, 문서 빠름, 정적 캐시, ISR 지원
getStaticPaths 빌드 타임 O 동적 라우트용 정적 생성 getStaticProps와 함께 사용
getServerSideProps 요청 시 X 로그인 페이지, 대시보드 매 요청마다 렌더링, 느릴 수 있음

 

상황 적절한 함수
자주 바뀌지 않는 콘텐츠 getStaticProps
동적 라우팅이 필요한 정적 페이지 getStaticProps + getStaticPaths
로그인 유저별 다른 데이터 getServerSideProps
페이지에 세션/쿠키 의존 getServerSideProps