[Next.js] Dynamic Routes - 동적 라우트

Next.js의 Dynamic Routes를 이해하기 쉽게 설명하겠습니다.

 


Dynamic Segments (동적 세그먼트)

  • 설명: 경로 일부가 동적으로 변할 수 있도록 설정하는 방식
  • 파일명 규칙: 대괄호([ ])로 감싼 파일명 사용
    • 예: [id].js, [slug].js
  • 폴더 구조
    pages/
      blog/
        [slug].js
    
  • 매칭되는 경로
    • /blog/a → slug = 'a'
    • /blog/b → slug = 'b'
  • 코드
    import { useRouter } from 'next/router';
    
    export default function BlogPost() {
      const router = useRouter();
      return <p>Post: {router.query.slug}</p>;
    }
    
  • 출력 결과
    • /blog/a → 화면에 Post: a
    • /blog/b → 화면에 Post: b

 

실제 개발에서는 "제품 상세 페이지"에서 활용할 수 있다.

-> 전자상거래 웹사이트에서 각 제품의 고유 ID를 기반으로 상세 페이지를 제공한다.

pages/
  blog/
    [slug].js

 

  • /product/123
    → 화면에 Product ID: 123

  • /product/456
    → 화면에 Product ID: 456

 

 

 

 

 

 

 


Catch-all Segments (전체 경로 처리)

  • 설명: 경로의 나머지 모든 부분을 배열 형태로 처리
  • 파일명 규칙: [...파일명].js
    • 예: [...slug].js
  • 폴더 구조
    pages/
      shop/
        [...slug].js
    
  • 매칭되는 경로
    • /shop/a → slug = ['a']
    • /shop/a/b → slug = ['a', 'b']
    • /shop/a/b/c → slug = ['a', 'b', 'c']
  • 코드
    import { useRouter } from 'next/router';
    
    export default function Shop() {
      const router = useRouter();
      const slug = router.query.slug || [];
      return <p>Path: {slug.join(' > ')}</p>;
    }
    
  • 출력 결과
    • /shop/a → 화면에 Path: a
    • /shop/a/b → 화면에 Path: a > b
    • /shop/a/b/c → 화면에 Path: a > b > c

 

해당 기능은 카테고리 및 하위 카테고리 페이지 개발에서 활용할 수 있다.

-> 쇼핑몰에서 카테고리와 하위 카테고리를 동적으로 처리

예를 들어, /shop/clothes/t-shirts 처럼 여러 경로를 처리할 수 있다.

pages/
  shop/
    [...categories].js
import { useRouter } from 'next/router';

export default function Categories() {
  const router = useRouter();
  const { categories = [] } = router.query;

  return (
    <div>
      <h1>Category Path:</h1>
      <p>{categories.join(' > ')}</p>
    </div>
  );
}
  • /shop/clothes
    → 화면에 Category Path: clothes

  • /shop/clothes/t-shirts
    → 화면에 Category Path: clothes > t-shirts

  • /shop/clothes/t-shirts/long-sleeve
    → 화면에 Category Path: clothes > t-shirts > long-sleeve

 

 

 

 

 


Optional Catch-all Segments (옵션 전체 경로 처리)

  • 설명: 경로가 없어도 기본값을 처리하며, 나머지 모든 경로도 배열 형태로 처리
  • 파일명 규칙: [[...파일명]].js
    • 예: [[...slug]].js
  • 폴더 구조
    pages/
      shop/
        [[...slug]].js
    
  • 매칭되는 경로
    • /shop → slug = undefined
    • /shop/a → slug = ['a']
    • /shop/a/b → slug = ['a', 'b']
  • 코드
    import { useRouter } from 'next/router';
    
    export default function Shop() {
      const router = useRouter();
      const slug = router.query.slug || [];
      if (slug.length === 0) {
        return <p>Welcome to the Shop</p>;
      }
      return <p>Path: {slug.join(' > ')}</p>;
    }
    
    • /shop → 화면에 Welcome to the Shop
    • /shop/a → 화면에 Path: a
    • /shop/a/b → 화면에 Path: a > b

 

블로그 메인 및 글 페이지에서 활용할 수 있다.

-> 블로그에서 메인 페이지와 개별 포스트, 또는 아카이브 페이지를 처리

pages/
  blog/
    [[...slug]].js
import { useRouter } from 'next/router';

export default function Blog() {
  const router = useRouter();
  const { slug } = router.query;

  if (!slug) {
    return <h1>Welcome to the Blog</h1>;
  }

  return (
    <div>
      <h1>Blog Path:</h1>
      <p>{Array.isArray(slug) ? slug.join(' > ') : slug}</p>
    </div>
  );
}

 

 

  • /blog
    → 화면에 Welcome to the Blog

  • /blog/2024/january
    → 화면에 Blog Path: 2024 > january

  • /blog/my-first-post
    → 화면에 Blog Path: my-first-post

 

 

요약 비교

라우터 종류 예시 경로 slug 결과 설명

Dynamic Segments /blog/a { slug: 'a' } 특정 값만 처리
Catch-all Segments /shop/a/b/c { slug: ['a', 'b', 'c'] } 경로의 나머지 전부 처리
Optional Catch-all Segments /shop { slug: undefined } 또는 [] 경로가 없어도 처리 가능, 나머지도 처리

 

'Next.js 개발 가이드 > 06. Learn Next.js 공식 가이드' 카테고리의 다른 글

[Next.js] Redirecting - 리다이렉팅  (0) 2024.12.31
16. 메타데이터 추가  (0) 2023.12.25
15. 인증  (0) 2023.12.25
14. 접근성 강화  (0) 2023.12.25
13. 에러 처리  (0) 2023.12.24
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유