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
/about.
Index routes
Files namedindex 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-postpages/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:- Predefined routes (
pages/blog/first-post.js) - Dynamic routes (
pages/blog/[slug].js) - Catch-all routes (
pages/blog/[...slug].js)
Linking between pages
Use theLink component from next/link to navigate between pages without a full page reload.
Linking to dynamic routes
Use string interpolation or a URL object for dynamic paths:Programmatic navigation
UseuseRouter for imperative navigation:
Shallow routing
Shallow routing updates the URL without re-running data fetching methods:getStaticProps or getServerSideProps.
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 agetLayout property to the page component:
pages/dashboard.tsx
pages/_app.tsx
API routes
Files insidepages/api/ become API endpoints. They run on the server and are never sent to the browser.
pages/api/hello.ts
/api/hello.
Handling HTTP methods
pages/api/posts.ts
Built-in request helpers
API routes expose parsed request data onreq:
req.cookies— cookies sent with the requestreq.query— parsed query stringreq.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
Createpages/404.tsx for a custom 404 page. It is statically generated at build time.
pages/404.tsx
500 page
Createpages/500.tsx for a custom server error page.
pages/500.tsx
