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
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.
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>;
}pages/docs/[...slug].js → Matches /docs/a, /docs/a/b, /docs/a/b/c
The slug param becomes an array of segments.
pages/index.js → /
pages/blog/index.js → /blog
_app.js→ Custom App component for global layout/styles._document.js→ Custom HTML document structure._error.js→ Custom error page.
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' });
}- 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.
- 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?