ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Routing in NextJS

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='21' AND `tutorial_submenu`='1742' AND `tutorial_status`=1 LIMIT 1

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

bash

/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

javascript

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

javascript

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

TypeExample RouteFile Location
Static Route/aboutpages/about.js
Dynamic Route/users/123pages/users/[id].js
Catch-All Route/blog/2024/march/postpages/blog/[...slug].js
API Route/api/hellopages/api/hello.js
Nested Route/blog/postpages/blog/post.js
Client-Side NavigationLink href="/about"import Link from "next/link"
Programmatic Navigationrouter.push("/dashboard")import { useRouter } from "next/router"

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql