Here’s a beginner-friendly guide to Next.js Routing, one of its most powerful and simple features for building modern React apps with file-based navigation.
🧭 What is Next.js Routing?
In Next.js, routing is file-based — meaning the file and folder structure inside the pages/
directory defines your app’s routes.
✅ No need for
react-router-dom
✅ Pages and URLs are automatically created for you
📁 File-based Routing Example
/pages
├── index.js → "/"
├── about.js → "/about"
└── blog
└── index.js → "/blog"
✅ This structure gives you:
/
→index.js
/about
→about.js
/blog
→blog/index.js
🔄 Client-Side Navigation with Link
Next.js uses its own Link
component for client-side routing:
import Link from 'next/link';
<Link href="/about">Go to About</Link>
✅ This avoids full page reloads and feels like an SPA.
🧩 Dynamic Routing
You can create dynamic routes using brackets:
Example:
/pages/post/[id].js
This matches:
/post/1
/post/hello-world
In [id].js
:
import { useRouter } from 'next/router';
export default function PostPage() {
const router = useRouter();
const { id } = router.query;
return <h1>Post ID: {id}</h1>;
}
🧠 Catch-All Routes
To match multiple segments:
/pages/docs/[...slug].js
Matches:
/docs/a
/docs/a/b/c
const { slug } = useRouter().query;
// slug = ['a', 'b', 'c']
⚙️ Nested Routes (Folders)
/pages
└── dashboard
├── index.js → /dashboard
└── settings.js → /dashboard/settings
Just create folders and files inside /pages/
.
🔁 Redirects and Rewrites (next.config.js)
module.exports = {
redirects() {
return [
{
source: '/old-blog',
destination: '/new-blog',
permanent: true,
},
];
},
};
✅ Handy for SEO and legacy support.
📦 API Routes (Bonus)
You can also define API endpoints right inside /pages/api/
/pages/api/hello.js → /api/hello
export default function handler(req, res) {
res.status(200).json({ message: 'Hello from API!' });
}
✅ Summary
Feature | Example |
---|---|
Static route | /about → about.js |
Dynamic route | /post/[id].js |
Nested route | /dashboard/settings |
Client navigation | <Link href="/page" /> |
API route | /api/hello.js |
Redirects/rewrites | In next.config.js |