0
0
NextjsHow-ToBeginner · 4 min read

How Routing Works in Next.js: Simple Guide with Examples

Next.js uses a file-based routing system where each file in the 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/about
  • pages/blog/[id].js/blog/:id
  • pages/api/hello.js → API endpoint /api/hello
javascript
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.

javascript
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!' })
}
Output
Visiting '/' shows: Welcome to the Home Page Visiting '/blog/42' shows: Blog Post ID: 42 Visiting '/api/hello' returns 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.

javascript
/* 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

FeatureDescriptionExample PathRoute URL
Static RouteFile maps to routepages/about.js/about
Dynamic RouteFile with [param] captures URL parampages/user/[id].js/user/:id
Catch-all RouteFile with [...param] captures multiple segmentspages/docs/[...slug].js/docs/*
API RouteBackend endpoint in pages/apipages/api/hello.js/api/hello

Key Takeaways

Next.js routing is file-based: each file in pages becomes a route automatically.
Use square brackets in filenames to create dynamic routes that capture URL parameters.
API routes live inside pages/api and must export a default function to handle requests.
Use Next.js Link component for client-side navigation to avoid full page reloads.
Common mistakes include wrong file naming and missing default exports in API routes.