Notes on Next.js App Router and Page Router

What is “Router”?

According to 1, the definitions of routers are different in various layers. In the application layer, a router is a path to a file that is rendered to open a page. It connects the URL pattern and the content seen by the user. A router is also being used in the network layer and API service.

There is a Next.js blog post 2 talk about the update of routing system in 2022.

Page Router

  • intuitive file-system router
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
projects
 ├── pages
 │   ├── api               # API
 │   │   ├── hello.tsx      # /api/hello
 │   │   └── users.tsx      # /api/users
 │   ├── posts
 │   │   ├── index.tsx      # /posts
 │   │   ├── [slug].tsx     # /posts/[dynamic path]
 │   │   └── create.tsx     # /posts/create
 │   ├── admin
 │   │   └── dashboard.tsx  # /admin/dashboard
 │   ├── _app.tsx
 │   ├── _document.tsx
 │   ├── index.tsx       # Homepage (/)

App Router

  • Next.js 13 introduced the new app router.
  • The official document is clear enough to understand the app router.
  • There are special files (layout, page, not-found, etc.) to create UI in route.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
project
 ├── app
 │   ├── layout.tsx            # Root layout (required)
 │   ├── page.tsx              # Home page (/)
 │   ├── blog
 │   │   ├── layout.tsx        # Blog layout
 │   │   ├── page.tsx          # Blog index (/blog)
 │   │   └── [slug]            # Dynamic blog route
 │   │       ├── page.tsx      # Individual blog page
 │   │       └── not-found.tsx # Custom 404 for blog
 │   ├── (auth)                # Route group (won't affect URL)
 │   │   ├── login
 │   │   │   └── page.tsx      # Login page (/login)
 │   │   └── register
 │   │       └── page.tsx      # Register page (/register)
 │   ├── api                   # API routes
 │   │   └── posts
 │   │       └── route.ts      # API endpoint
 │   └── _components           # Private components (not routable)
 │       └── Navbar.tsx

Reference

Built with Hugo
Theme Stack designed by Jimmy