본문 바로가기
프런트엔드/리엑트

Next.js 입문기 - 초보자가 직접 따라하며 배운 실습 기록 ( 2 )

by Alan__kang__morlang 2025. 4. 19.
반응형

학습 목표

Next.js에서는 페이지를 렌더링할 때 필요한 데이터를 빌드 타임, 요청 시, 정적 경로 생성 등 다양한 방식으로 가져올 수 있습니다.

이번 글에서는 세 가지 주요 방식에 대해 예제를 통해 실습하며 익혀보았습니다.

데이터 패칭 방식 비교

메서드 실행 시점 특징
getStaticProps 빌드 시 정적인 페이지를 미리 생성함 (SSG)
getServerSideProps 요청 시 요청마다 서버에서 데이터를 가져옴 (SSR)
getStaticPaths + getStaticProps 빌드 시 + 동적 경로 동적 경로를 정적으로 생성 (블로그, 상품 등)

실습 1: getStaticProps

정적인 HTML 페이지를 빌드 타임에 생성합니다.

// pages/static-props.js
export async function getStaticProps() {
  return {
    props: {
      today: new Date().toLocaleDateString(),
      message: "정적으로 생성된 페이지입니다!",
    },
  };
}

export default function StaticPropsPage({ today, message }) {
  return (
    <div>
      <h1>{message}</h1>
      <p>오늘 날짜는: {today}</p>
    </div>
  );
}

접속 경로: /static-props

실습 2: getServerSideProps

요청 시마다 서버에서 실행되어 데이터를 가져옵니다.

// pages/server-props.js
export async function getServerSideProps() {
  const now = new Date().toLocaleTimeString();

  return {
    props: {
      now,
    },
  };
}

export default function ServerSidePage({ now }) {
  return (
    <div>
      <h1>서버에서 받아온 현재 시간:</h1>
      <p>{now}</p>
    </div>
  );
}

접속 경로: /server-props

실습 3: getStaticPaths + getStaticProps

동적 라우팅을 미리 정적으로 생성합니다.

// pages/posts/[slug].js
export async function getStaticPaths() {
  return {
    paths: [
      { params: { slug: 'hello' } },
      { params: { slug: 'world' } },
    ],
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  return {
    props: {
      slug: params.slug,
    },
  };
}

export default function PostPage({ slug }) {
  return (
    <div>
      <h1>게시글: {slug}</h1>
    </div>
  );
}

접속 경로: /posts/hello, /posts/world

외부 데이터 로직 분리 팁

// lib/postService.js
export class PostService {
  static getSlugs() {
    return ['hello', 'world'];
  }
}

// pages/posts/[slug].js
import { PostService } from '../../lib/postService';

export async function getStaticPaths() {
  const slugs = PostService.getSlugs();

  return {
    paths: slugs.map((slug) => ({
      params: { slug },
    })),
    fallback: false,
  };
}

언제 어떤 방식을 써야 할까?

사용 상황 추천 방식
거의 바뀌지 않는 콘텐츠 getStaticProps
자주 바뀌는 실시간 데이터 getServerSideProps
여러 동적 경로를 정적 생성 getStaticPaths + getStaticProps

다음 단계 예고

Next.js에서는 페이지뿐 아니라 /api/* 경로로 API도 만들 수 있습니다.

다음 단계에서는 백엔드 없이도 서버리스 API를 직접 구성하고, 프론트엔드에서 데이터를 주고받는 실습을 진행합니다.

 

반응형