참치코더의 꿈 메모장

Next.js / 라우팅 기본 정리 (ver 12- , ver13+) 비교 본문

Next.js

Next.js / 라우팅 기본 정리 (ver 12- , ver13+) 비교

참치깡 2025. 9. 20. 19:19
728x90

 

제미나이가 생성한 Next.js 로고 이미지

 

Next.js는 파일 시스템 기반 라우팅을 사용한다.

app/  또는 pages/ 폴더에 파일/폴더를 만들면 자동으로 URL 경로가 된다.

 

Next.js 13+

 

app/ (13 버전 이상은 app으로 명시)

--page.tsx -> "/" (홈)

-- about/

     ㄴ page.tsx -> "/about"

-- posts/

     ㄴpage.tsx -> "/posts"

     ㄴ[postId]/

             ㄴ page.tsx -> "/posts/1" , "/posts/2",  "/posts/3" 같은 동적 라우트

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// app/about/page.tsx
 
export default function AboutPage(){
    return <h1>About 페이지</h1>;
}
 
// app/posts/[postId]/page.tsx
 
interface PageProps {
    params : {postId: string};
}
 
export default function PostPage({params}: PageProps){ // porps.Parmas = {params} 구조 분해 할당 
    return <h1>포스트 ID: {params.postId}</h1>;
}
 
// /posts/123 접속 시 params.postId === "123"
 
// 쿼리 스트링 받기
 
// app/search/page.tsx
interface PageProps {
    searchParams : {data?: string}; // data? 라고 한다면 data 값이 있어도 되고 없어도 된다.
}
 
export default function SearchPage({ searchParams } : PageProps){
    return <h1>검색어: {searchParams.data}</h1>;
}
 
// /search?data=food => "food"
 
 
 
cs

 

레이아웃(layout.tsx)은 해당 경로의 모든 하위 페이지에 적용된다.

 

app/ (13 버전 이상은 app으로 명시)

--page.tsx -> "/" (홈)

ㄴ layout.tsx -> 전체 레이아웃

-- about/

     ㄴ page.tsx -> "/about"

     ㄴ layout.tsx -> /about/* 에만 적용되는 레이아웃

-- posts/

     ㄴpage.tsx -> "/posts"

     ㄴ layout.tsx -> /page/* 에만 적용되는 레이아웃

     ㄴ[postId]/

             ㄴ page.tsx -> "/posts/1" , "/posts/2",  "/posts/3" 같은 동적 라우트

 

Next.js 12-

 

pages/ (12 버전 이하은 pages으로 명시)

--index.tsx -> "/" (홈)

-- about.tsx -> "/about"

-- posts/

     ㄴ[postId].tsx

             ㄴ "/posts/1" , "/posts/2",  "/posts/3" 같은 동적 라우트

1
2
3
4
5
6
7
8
9
10
// pages/posts/[postId].tsx
import { useRouter } from 'next/router';
 
export default function PostPage() {
  const router = useRouter();
  const { postId } = router.query;
 
  return <h1>포스트 ID: {postId}</h1>;
}
 
cs

 

728x90
Comments