In Next.js, the App Router is used to define and structure an application’s routes and their UIs. It is defined by creating a folder named app
at the project’s root level.
In the Next.js App Router, folders define path segments, and reserved files within, like page.tsx
, define that segment’s UI.
├── app│ ├── users /users│ │ ├── page.tsx UI│ ├──settings /settings└── │ ├── page.tsx UI
In Next.js, nested routes can be created by creating nested folders.
├── app│ ├── users│ │ ├── profiles /users/profiles└── │ │ ├── page.tsx UI
A URL path is composed of path segments and comes after the URL domain.
For example, in the URL https://www.codecademy.com/catalog/language/javascript
:
codecademy.com
is the domain./catalog/language/javascript
is the path./catalog
, /language
, and /javascript
are path segments.Next.js provides SPA-like navigation with the useRouter()
hook and <Link>
component.
The useRouter()
hook returns a router
object which contains methods like push(path)
, back()
, and forward()
for navigation.
The <Link>
component extends the <a>
element by adding features like prefetching.
'use client'import { useRouter } from 'next/navigation'import Link from 'next/link'export default function MyPage() {const router = useRouter()return (<div><Link href="/">Home</Link><button onClick={router.back}>Back</button></div>)}
page.tsx
In Next.js, a page.tsx
is a reserved file that defines a unique UI for its containing path segment and makes it accessible.
To use page.tsx
, you must default export a React component.
// in page.tsx in the folder /app/settingsexport default function SettingsPage() {return (<h1>Your Settings</h1>)}
layout.tsx
and template.tsx
In Next.js, layout.tsx
and template.tsx
are reserved files used to create shared UIs.
Similarities include:
children
prop of type ReactNode
. Differences include:
template.tsx
component will be re-instantiated while layout.tsx
component will not. layout.tsx
returning the <html>
and <body>
elements is required in the App Router.// In root layout.tsxexport default function RootLayout({children}: { children: React.ReactNode}) {return (<html><body><h1>Root Layout</h1>{children}</body></html>)}// In template.tsxexport default function Template({children}: {children: React.ReactNode}) {return (<h2>Template Layout</h2>{children})}
In Next.js, a dynamic segment is created by wrapping a folder’s name in square brackets, for example, /app/users/[userId]
.
The page.tsx
component exported from this folder will receive a params
prop which will contain the dynamic segment data (as a string
) and be referenced using the dynamic segment folder name (userId
).
// In /app/users/[userId]/page.tsxexport default function UserPage({ params }: { params: { userId: string }}) {const userId = params.userId // Access dynamic segment datareturn (<h2>My User Page for: {userId}</h2>)}
In Next.js, dynamic segments can be further modified to be made catch-all and optional. A catch-all segment is created by prefixing a dynamic segment with ellipses like /app/articles/[...articleIds]
.
A catch-all segment’s page.tsx
component will receive a params
prop containing the dynamic data as an array of string
s referenced using the dynamic folder name (articleIds
).
To make the catch-all dynamic segment optional, you wrap it in another pair of square brackets like: /app/articles/[[...articleIds]]
.
// In /app/articles/[[...articleIds]]/page.tsxexport default function ArticlesPage({ params }: { params: { articleIds: string[]}}) {const articleIds = params.articleIds // Retrieve dynamic segment datareturn (<><h2>Articles</h2>{articleIds.map(id => (<p>Article Id is: {id}</p>))}</>)}
Next.js reserves special files used to define UIs by default exporting a React component. Some of the special files include:
layout.tsx
: Defines a shared UI.template.tsx
: Defines a shared UI.error.tsx
: Defines an ErrorBoundary
fallback UI.loading.tsx
: Defines a Suspense
fallback UI. not-found.tsx
: Defines an ErrorBoundary
fallback UI for an unknown segment or nested segments.Next.js defines a component hierarchy for reserve file components. The hierarchy is:
layout.tsx
template.tsx
error.tsx
loading.tsx
not-found.tsx
page.tsx
Any nested hierarchy will be placed within the hierarchy of its parent.