Dynamic Routing in NextJS
🚀 Dynamic Routing in Next.js
Dynamic Routing in Next.js allows us to create flexible, URL-based pages using file-based routing.
📌 1. What is Dynamic Routing?
Unlike static routes (/about or /contact), dynamic routes are used when the URL changes based on data, such as:
Blog posts:
/blog/:idUser profiles:
/user/:usernameProduct pages:
/products/:slug
✅ Next.js handles dynamic routes using square brackets [ ] inside the pages directory.
📌 2. Creating a Dynamic Route
🔹 Example: Blog Post Page (pages/blog/[id].js)
<h1>Slug: {slug?.join("/")}<h1>{slug ? `Slug: ${slug.join("/")}` : "Blog Homepage"}<ul> {posts.map((post) => ( <li key={post.id}> <Link href={`/blog/${post.id}`}> <a>{post.title}</a> </Link> </li> ))} </ul> );}
✅ Client-side navigation for faster UX
📌 8. Summary: Choosing the Right Dynamic Routing Method
| Method | Best For | Performance |
|---|---|---|
useRouter().query | Client-side navigation | 🔥 Fast |
getServerSideProps | Real-time dynamic pages | 🐢 Slower |
getStaticProps + getStaticPaths | Pre-rendered pages | ⚡ Super Fast |
[...slug].js | Catch-all dynamic routes | 🚀 Flexible |