Skip to main content
The Pages Router uses a file-system based router. Every file you add to the pages/ directory becomes a route.

Defining routes

A page is a React component exported from a .js, .jsx, .ts, or .tsx file in the pages/ directory. The file path determines the URL.
pages/about.tsx
This page is accessible at /about.

Index routes

Files named index map to the root of their directory:
  • pages/index.js/
  • pages/blog/index.js/blog

Nested routes

Nested folders create nested routes:
  • pages/blog/first-post.js/blog/first-post
  • pages/dashboard/settings/username.js/dashboard/settings/username

Dynamic routes

Wrap a filename in square brackets to create a dynamic segment.
pages/blog/[slug].tsx

Catch-all routes

Add ... inside brackets to match multiple path segments:

Optional catch-all routes

Double brackets make the parameter optional. The route also matches when the segment is absent:

Route precedence

When multiple route patterns match a URL, Next.js uses this order of precedence:
  1. Predefined routes (pages/blog/first-post.js)
  2. Dynamic routes (pages/blog/[slug].js)
  3. Catch-all routes (pages/blog/[...slug].js)

Linking between pages

Use the Link component from next/link to navigate between pages without a full page reload.
Links in the viewport are prefetched automatically for pages using Static Generation.

Linking to dynamic routes

Use string interpolation or a URL object for dynamic paths:

Programmatic navigation

Use useRouter for imperative navigation:

Shallow routing

Shallow routing updates the URL without re-running data fetching methods:
This is useful for updating query parameters without triggering getStaticProps or getServerSideProps.
Shallow routing only works for URL changes within the current page. If you shallow-route to a different page, the new page loads normally.

Layouts

Single shared layout

Wrap your entire application in a layout using _app.js:
pages/_app.tsx

Per-page layouts

For pages that need different layouts, add a getLayout property to the page component:
pages/dashboard.tsx
pages/_app.tsx

API routes

Files inside pages/api/ become API endpoints. They run on the server and are never sent to the browser.
pages/api/hello.ts
This handler is accessible at /api/hello.

Handling HTTP methods

pages/api/posts.ts

Built-in request helpers

API routes expose parsed request data on req:
  • req.cookies — cookies sent with the request
  • req.query — parsed query string
  • req.body — parsed request body

Dynamic API routes

API routes support the same dynamic segment syntax as page routes:
pages/api/post/[pid].ts
In the App Router, Route Handlers replace API routes and support streaming, Web API request/response objects, and more.

Custom error pages

404 page

Create pages/404.tsx for a custom 404 page. It is statically generated at build time.
pages/404.tsx

500 page

Create pages/500.tsx for a custom server error page.
pages/500.tsx