
Routing in NextJS
🚀 Routing in Next.js
Next.js provides a powerful file-based routing system that makes navigation and dynamic routing easy. This guide covers static, dynamic, nested, API, and imperative routing in Next.js.
📌 1. Basic Routing (Pages as Routes)
In Next.js, the pages/
directory automatically generates routes based on file structure.
🔹 Example: Creating Pages
/pages ├── index.js → <h1>About Pageimport { useRouter } from "next/router";export default function UserProfile() { const router = useRouter(); const { id } = router.query; return <h1>Profile of User {id}import { useRouter } from "next/router";export default function BlogPost() { const router = useRouter(); const { slug } = router.query; return <h1>Blog Path: {slug?.join("/")}export default function BlogPost() { return <h1>Blog Postexport default function handler(req, res) { res.status(200).json({ message: "Hello, API!" });}
✅ Making a GET request to /api/hello
returns { "message": "Hello, API!" }
📌 6. Navigating Between Pages
Use next/link
for client-side navigation.
🔹 Example: Client-Side Navigation
import Link from "next/link";export default function Home() { return ( <nav> <button import { NextResponse } from "next/server";export function middleware(req) { if (!req.cookies.token) { return NextResponse.redirect(new URL("/login", req.url)); }}
✅ Unauthenticated users are redirected to /login
📌 10. Router Caching for Faster Navigation
Next.js caches previously visited routes to speed up navigation.
🔹 Example: Prefetching Routes
import Link from "next/link";export default function Home() { return ( <Link href="/profile" prefetch> Go to Profile </Link> );}
✅ Prefetches /profile
in the background
🚀 Summary: Routing in Next.js
Type | Example Route | File Location |
---|---|---|
Static Route | /about | pages/about.js |
Dynamic Route | /users/123 | pages/users/[id].js |
Catch-All Route | /blog/2024/march/post | pages/blog/[...slug].js |
API Route | /api/hello | pages/api/hello.js |
Nested Route | /blog/post | pages/blog/post.js |
Client-Side Navigation | Link href="/about" | import Link from "next/link" |
Programmatic Navigation | router.push("/dashboard") | import { useRouter } from "next/router" |