NextJS의 Routing
Create React App으로 작업할 때는 클라이언트 사이드 라우팅을 하기 위해 react-router-dom을 사용했다.
나만 그랬는지 모르겠지만 react-router-dom을 사용함으로써 추가되는 코드나 발생하는 에러가 참 많았다.
불편했다.
하지만 Next를 사용하면 이런 불편함이 없다. 왜냐하면 next는 파일시스템 기반 라우터가 있기 때문이다!
공식문서에 따르면 pages 폴더에 파일을 만들면 자동으로 라우트를 사용할 수 있다.
Index Routes
index라는 이름은 자동으로 해당 디렉토리의 root폴더가 된다.
- pages/index.js → /
- pages/blog/index.js → /blog
Nested Routes
폴더안에 파일을 만드는 방식으로 중첩된 폴더구조를 만들게 되면 자동으로 라우팅됩니다.
- pages/blog/first-post.js → /blog/first-post
- pages/dashboard/settings/username.js → /dashboard/settings/username
Dynamic Route Segments
대괄호를 사용하면 동적 라우팅을 사용할 수 있다.
- 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)
Linking between pages
SPA처럼 page를 변경할 때 클라이언트 사이드 라우팅을 사용할 수 있다. (새로고침 없이 SPA처럼 페이지 변경 가능)
next/link를 import해서 Link component를 사용한다.
Dynamic Routes
복잡한 애플리케이션에서는 동적 라우팅이 필수적이다. 위에서 설명했듯이 대괄호[]를 사용해서 동적 라우팅을 구현할 수 있다.
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
return <p>Post: {pid}</p>
}
export default Post
위 컴포넌트가 pages/post/[pid].js 라고 가정하면
localhost:3000/post/2 혹은 localhost:3000/post/abc 와 같은 모든 라우트와 매칭 된다.
그리고 그 pid는 query 파라미터로 전달된다.
pages/post/[pid]/[comment].js라면
localhost:3000/post/abc/a-comment와 매칭된다. 그리고
{ "pid": "abc", "comment": "a-comment" }
이런 파라미터로 전달받는다.
Catch all routes
대괄호 안에 ...(점 세개)를 추가하면 모든 path를 잡을 수 있는 dynamic routes가 된다.
/pages/post/[...pid].js 는 localhost:3000/post/a, localhost:3000/post/a/123/bcd 와 모두 매칭된다.
파라미터도 배열로 받는다.
{ "pid": ["a", "123", "bcd"] }
Optional Catch all routes
대괄호 두 개를 겹쳐 쓰고 안에... 까지 추가하면 optional한 catch all route가 된다.
예를들면..
/pages/post/[[...pid]].js 는 localhost:3000/post/a, localhost:3000/post/a/123/bcd,
심지어 localhost:3000/post까지 매칭된다.
옵셔널을 사용하게 되면 파라미터가 없는 라우터까지 매칭 된다는 것이다.
{ } // GET `/post` (empty object)
{ "pid": ["a"] } // `GET /post/a` (single-element array)
{ "pid": ["a", "123", "bcd"] } // `GET /post/a/123/bcd` (multi-element array)
주의사항
사전 정의된 라우트는 동적 라우트보다 우선권을 가지고, 동적 라우트는 Catch all 라우트 보다 우선권을 가진다.
- pages/post/create.js - Will match /post/create
- pages/post/[pid].js - Will match /post/1, /post/abc, etc. But not /post/create
- pages/post/[...slug].js - Will match /post/1/2, /post/a/b/c, etc. But not /post/create, /post/abc
ㅇㅇ 우선권
https://nextjs.org/docs/routing/introduction
Routing: Introduction | Next.js
Next.js has a built-in, opinionated, and file-system based Router. You can learn how it works here.
nextjs.org