NextJs - v13 App Router

App Router

  • App Router is introduced in NextJs v13, built on React Server Components (RSC).
  • By default, components inside app are React Server Components.
  • The app directory works alongside the pages directory to allow for incremental adoption.
  • As users navigate around the app, the router will store the result of the RSC payload in an in-memory client-side cache

File-system based router

  • Folders are used to define routes.
  • A route is a single path of nested folders.
  • Each folder represents a route segment that maps to a URL segment.
  • To create a nested route, you can nest folders inside each other.

NextJS Reserved Files Conventions

  • layout: Shared UI for a segment and its children
  • page: Unique UI of a route and make routes publicly accessible
  • loading: Loading UI for a segment and its children (React suspense boundary)
  • not-found: Not found UI for a segment and its children (React error boundary)
  • error: Error UI for a segment and its children (React error boundary)
  • global-error: Global Error UI
  • route: Server-side API endpoint
  • template: Specialized re-rendered Layout UI
  • default: Fallback UI for Parallel Routes

Root layouts (required)

  • The top-most layout
  • Root layouts must contain html and body tags.
  • This layout is shared across all pages in an application.
  • Any route segment can optionally define its own Layout.

Layout

  • A layout is UI that is shared between multiple pages.
  • On navigation, layouts preserve state, remain interactive.
  • Do not re-render.
  • Can be nested.

Page

  • Only the contents returned by page.js or route.js are publically addressable.

Loading

Sample Structure

├── app
│   ├── dashboard (routable)
│   │   ├── page.tsx
│   │   ├── loading.tsx
│   │   ├── layout.tsx
│   │   ├── settings.tsx
│   ├── api (routable)
│   │   ├── route.ts
│   │   ├── db.ts
│   ├── lib
│   │   ├── utils.ts
│   │   ├── constants.ts
│   ├── components
│   │   ├── button.tsx
│   │   ├── card.tsx
│   │   ├── input.tsx
│   │   ├── label.tsx
│   │   ├── skeleton.tsx
│   │   ├── tabs.tsx
│   ├── layout.tsx (root layout)
│   ├── page.tsx
├── public
│   ├── next.svg
│   ├── vercel.svg
├── next.config.js
├── .env.local
├── .env.development
├── .env.staging
├── .env.production
├── .eslintrc.json
├── tailwind.config.js
├── tsconfig.json
├── package.json
├── package-lock.json
├── postcss.config.js
├── README.md
└── .gitignore

More Advanced Routing

  1. Route Groups
  2. Parallel Routes
  3. Intercepting Routes