✍ 공부/NextJS

[ TIL ] Next.js 동적 라우팅 ( Dynamic Routing )

Po_tta_tt0 2022. 3. 19. 20:44
반응형

 

 

 

 

✍ Next.js에서의 라우팅

 

Next에서는 Static Routing(정적 라우팅)과 Dynamic Routing(동적 라우팅)을 지원한다.

 

 

<공식문서>

Next.js has a file-system based router built on the concept of pages.
When a file is added to the pages directory, it's automatically available as a route.
The files inside the pages directory can be used to define most common patterns.

Next.js는 파일 시스템 기반의 라우팅을 해준다

pages 경로에 파일을 추가하면 자동적으로 route할 수 있다

=> Next.js 프로젝트 안의 'pages' 라는 폴더에 라우팅하고 싶은 이름으로 된 파일을 만들어주면 되는 것.

=> 자연스럽게 우리가 만든 파일 이름을 주소로 라우팅되는 것이 정적 라우팅이다.

 

 

 

📌 Dynamic Routing(동적 라우팅)

 

아래는 Next.js에서 동적 라우팅을 할 수 있는 몇가지 방법이다.

  • pages/blog/[slug].js  /blog/:slug (/blog/hello-world)
  • pages/[username]/settings.js  /:username/settings (/foo/settings)
  • pages/post/[...all].js  /post/* (/post/2020/id/title)

 

🙌 [대괄호]

<pages/post/[pid].js>

=> pages 안에 post라는 폴더를 만들고 그 안에 [pid].js 파일을 만들었다.

 

/post/1 , /post/abc 등의 주소는 모두 post/[pid].js로 매칭된다.

대괄호 안의 임의의 이름은 라우터 객체의 query 속성으로 들어간다.

 

query

경로 : /post/abc

query 객체 : { "pid": "abc" }

 

경로 : /post/abc?foo=bar

query 객체 : { "foo": "bar", "pid": "abc" }

 

 

 

 

🙌 Catch all routes : [ . . . 대괄호] 

동적 라우팅은 만드는 파일 대괄호 안에 '...'을 찍어줌으로서 이 후 모든 경로를 잡아낼 수 있다.

<pages/post/[...pid].js>

=> pages 안에 post라는 폴더를 만들고 그 안에 [...pid].js 파일을 만들었다

 

이 파일은 ant path까지 잡아낼 수 있다

/post/1 , /post/abc, /post/abc/124/4635/efwef까지 모두 post/[...pid].js로 매칭된다

 

query

경로 : /post/abc

query 객체 : { "pid": ["abc"] }

 

경로 : /post/abc/123

query 객체 : { "pid": ["abc", "123"] }

 

 

 

 

🙌 Optional catch all routes : [ [ . . . 대괄호] ]

파일 이름을 이중 대괄호 안에 ...을 포함하여 작성해준다.

<pages/post/[[...pid]].js>

/post/1 , /post/abc, /post/abc/124/4635/efwef에 /post까지 모두 post/[...pid].js로 매칭된다

 

 

 

 

 

 

🙇‍♀️ Super Thanks !

https://nextjs.org/docs/routing/dynamic-routes

https://soft91.tistory.com/88

https://steadily-worked.tistory.com/601

 

반응형