Skip to content

Latest commit

 

History

History
98 lines (60 loc) · 2.13 KB

File metadata and controls

98 lines (60 loc) · 2.13 KB

File-based Routing in Next.js

What is File-based Routing?

In Next.js, the file structure inside the pages/ directory defines your app’s routes automatically — no need to manually configure a router like in React Router.

Each file’s path corresponds directly to a URL path.

Example: pages/about.js/about

Nested folders become nested routes: pages/blog/post.js/blog/post


How it Works

Next.js scans the pages/ directory at build time and creates routes based on:

  • File name → URL
  • Folder structure → Nested paths

When you add or rename a file in pages/, the route updates automatically.


Special Routing Features

A. Dynamic Routes

Files/folders wrapped in square brackets ([param]) become dynamic segments.

Example: pages/blog/[id].js/blog/1, /blog/abc

import { useRouter } from 'next/router';

export default function BlogPost() {
  const router = useRouter();
  const { id } = router.query;
  return <h1>Blog Post {id}</h1>;
}

B. Catch-all Routes

pages/docs/[...slug].js → Matches /docs/a, /docs/a/b, /docs/a/b/c

The slug param becomes an array of segments.


C. Index Routes

pages/index.js/ pages/blog/index.js/blog


D. Special Files

  • _app.js → Custom App component for global layout/styles.
  • _document.js → Custom HTML document structure.
  • _error.js → Custom error page.

E. API Routes

Any file inside pages/api/ becomes an API endpoint.

Example: pages/api/hello.js/api/hello

export default function handler(req, res) {
  res.status(200).json({ message: 'Hello API' });
}

Benefits

  • No manual route configuration.
  • Predictable — folder structure matches URL structure.
  • Supports static & dynamic routes easily.
  • API routes co-exist with page routes in the same project.

Interview Tip — Common Questions

  • How do you create dynamic routes in Next.js?
  • What’s the difference between [param] and [...param] in routing?
  • How do API routes work in file-based routing?
  • How do you get query parameters in a Next.js page?