How Routing Works in Next.js: Simple Guide with Examples
pages folder automatically becomes a route. Dynamic routes use square brackets like [id].js to capture URL parameters, and API routes are created inside pages/api for backend endpoints.Syntax
Next.js routing is based on the pages directory structure. Each file corresponds to a route path. Dynamic routes use square brackets to capture variables from the URL. API routes live inside pages/api and handle backend logic.
pages/index.js→/pages/about.js→/aboutpages/blog/[id].js→/blog/:idpages/api/hello.js→ API endpoint/api/hello
pages/index.js export default function Home() { return <h1>Home Page</h1> } pages/blog/[id].js import { useRouter } from 'next/router' export default function Post() { const router = useRouter() const { id } = router.query return <h1>Post ID: {id}</h1> } pages/api/hello.js export default function handler(req, res) { res.status(200).json({ message: 'Hello from API' }) }
Example
This example shows a simple Next.js app with a homepage, a dynamic blog post page, and an API route. The homepage is at /, the blog post page uses the URL parameter id like /blog/123, and the API route returns JSON at /api/hello.
pages/index.js export default function Home() { return <h1>Welcome to the Home Page</h1> } pages/blog/[id].js import { useRouter } from 'next/router' export default function BlogPost() { const router = useRouter() const { id } = router.query return <h1>Blog Post ID: {id}</h1> } pages/api/hello.js export default function handler(req, res) { res.status(200).json({ greeting: 'Hello from Next.js API!' }) }
Common Pitfalls
1. Forgetting to restart the dev server: Adding new files in pages usually hot reloads, but sometimes a restart is needed.
2. Misnaming dynamic routes: Use square brackets exactly like [param].js, not curly braces or other syntax.
3. Using client-side navigation incorrectly: Use Next.js Link component for navigation to avoid full page reloads.
4. API routes must export a default function: Otherwise, Next.js won't recognize the endpoint.
/* Wrong dynamic route file name */ pages/blog/{id}.js // ❌ invalid syntax /* Correct dynamic route file name */ pages/blog/[id].js // ✅ valid syntax /* Wrong API route export */ export function handler(req, res) { res.status(200).json({ message: 'Hi' }) } // ❌ no default export /* Correct API route export */ export default function handler(req, res) { res.status(200).json({ message: 'Hi' }) } // ✅ default export
Quick Reference
| Feature | Description | Example Path | Route URL |
|---|---|---|---|
| Static Route | File maps to route | pages/about.js | /about |
| Dynamic Route | File with [param] captures URL param | pages/user/[id].js | /user/:id |
| Catch-all Route | File with [...param] captures multiple segments | pages/docs/[...slug].js | /docs/* |
| API Route | Backend endpoint in pages/api | pages/api/hello.js | /api/hello |