Dynamic routing is a crucial feature of modern web development, allowing websites to scale effortlessly by generating routes dynamically rather than predefining them. Next.js provides a robust routing system, empowering developers to create dynamic pages that cater to a wide range of user inputs, such as unique product pages, user profiles, or content-heavy blogs.
This guide explores dynamic routes in Next.js, breaking down step-by-step how they work, how to implement them, and what benefits they bring to your application.
Dynamic routes refer to routes that aren’t hard-coded. Instead, they are generated based on variables or parameters, such as user IDs, product categories, or blog post slugs. Unlike static routes, where each path is predefined, dynamic routes create paths based on the data provided at runtime.
For instance, if you're building an e-commerce website, instead of creating individual pages for each product (/products/1
, /products/2
), you can set up a dynamic route (/products/[id]
) that adapts to any product ID.
Next.js simplifies dynamic routing using square brackets in file names, making it easier to generate flexible, parameterized routes with minimal effort.
In Next.js, creating dynamic routes is straightforward. Let's walk through the process of building your first dynamic route in Next.js:
Start by initializing a Next.js project using the following commands:
npx create-next-app@latest
cd my-next-app
npm run dev
This creates a basic Next.js app, with all the essential files and dependencies installed.
Inside the pages
directory, create a new folder named products
and, within it, a new file [id].js
. The square brackets [id]
represent a dynamic segment in the URL, where id
is the parameter that will vary based on the request.
// pages/products/[id].js
import { useRouter } from "next/router";
const ProductPage = () => {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>Product ID: {id}</h1>
</div>
);
};
export default ProductPage;
Now, if you visit /products/1
, /products/2
, etc., Next.js will dynamically render the product page based on the URL parameter.
Next.js allows you to fetch data specific to the dynamic parameter using getStaticProps
and getStaticPaths
. This approach is particularly useful for pre-rendering pages during the build process.
We'll dive deeper into this in the getStaticPaths section.
Dynamic route parameters open up a world of possibilities for creating rich, data-driven applications. These parameters are extracted from the URL and can be used to fetch specific content, user information, or display results based on user input.
You can add multiple dynamic parameters by nesting files within folders. For example, if you want a route like /products/[category]/[id]
, you can create the following file structure:
/pages/products/[category]/[id].js
Within the code, you can now access both category
and id
from router.query
.
const ProductPage = () => {
const router = useRouter();
const { category, id } = router.query;
return (
<div>
<h1>Category: {category}</h1>
<h2>Product ID: {id}</h2>
</div>
);
};
Dynamic route parameters are essential for building:
/products/[id]
)/users/[username]
)/blog/[slug]
)In large applications, you might need to handle nested dynamic routes to create complex page hierarchies. Next.js allows you to nest dynamic routes seamlessly.
For instance, consider a URL structure for an e-commerce store:
/products/[category]/[subcategory]/[id]
This structure helps in organizing content based on categories and subcategories. To achieve this, you’ll organize your pages
directory like this:
/pages/products/[category]/[subcategory]/[id].js
Inside the [id].js
file, you can access all the parameters (category
, subcategory
, id
) using router.query
.
This is especially useful when working with deep content hierarchies, like news websites or e-commerce platforms with multiple product categories.
Dynamic API routes in Next.js enable you to build flexible, server-side APIs without configuring a separate backend framework. You can create dynamic endpoints that adapt based on the URL.
Create a new API route in the pages/api
directory, using the [id].js
naming convention:
// pages/api/products/[id].js
export default function handler(req, res) {
const { id } = req.query;
res.status(200).json({ productId: id });
}
This will return a JSON response containing the product ID whenever a request is made to /api/products/[id]
.
You can now use this dynamic API route in your frontend code to fetch product data dynamically based on the URL parameter.
Dynamic API routes make it simple to create endpoints for user profiles, product details, or any other dynamic resource, without manually defining each route.
In Next.js, getStaticPaths
is a function that works in tandem with getStaticProps
to pre-render pages with dynamic routes at build time. It’s particularly useful for optimizing SEO and performance, as it allows you to generate pages ahead of time for specific dynamic paths.
When using getStaticPaths
, you define the paths that should be pre-rendered during the build process. For example, in a blog, you might pre-render the most popular posts.
// pages/products/[id].js
export async function getStaticPaths() {
const paths = [
{ params: { id: "1" } },
{ params: { id: "2" } },
{ params: { id: "3" } },
];
return {
paths,
fallback: false, // If false, any paths not returned by getStaticPaths will result in a 404 page.
};
}
export async function getStaticProps({ params }) {
const { id } = params;
return {
props: { productId: id },
};
}
Using this approach ensures that your dynamic routes are rendered quickly, improving both user experience and search engine rankings.
Dynamic routing offers flexibility, while static routing ensures predictability and
performance. Let’s break down the key benefits of each.
Both approaches have their use cases, but dynamic routes are more suited to applications where content changes frequently, such as blogs, e-commerce stores, or social platforms.
Dynamic routes can be highly beneficial for SEO, especially when paired with Next.js’s pre-rendering capabilities. However, you need to carefully manage how search engines discover and index dynamic content.
/products/[id]
should use slugs or names instead of numeric IDs.Following these best practices helps search engines better understand and rank your dynamic pages, driving more traffic to your site.
Next.js 12 introduced middleware to enable more advanced routing use cases. Middleware allows you to execute code before a request is completed, making it perfect for adding authentication checks, rewriting URLs, or handling localization.
// middleware.js
export function middleware(req) {
const url = req.nextUrl.clone();
if (!url.pathname.startsWith("/products")) {
url.pathname = `/products/redirected`;
}
return NextResponse.redirect(url);
}
This allows you to redirect users based on conditions or add custom logic to your routing system.
Dynamic routes can introduce unexpected errors, especially when dealing with missing data or incorrect parameters. Here are a few best practices to handle errors effectively:
Next.js automatically generates a 404 page for non-existent dynamic routes, but you can customize it:
// pages/404.js
export default function Custom404() {
return <h1>Page Not Found</h1>;
}
Use React’s Error Boundaries to catch errors in dynamic components and gracefully display error messages.
Thoroughly testing dynamic routes is crucial for ensuring smooth navigation and functionality. Here’s how you can approach testing:
Test the components rendered by your dynamic routes to ensure they behave correctly when different parameters are passed.
Use tools like Cypress to simulate user interactions with dynamic routes, ensuring that navigation and data fetching work seamlessly.
// Example Cypress Test
describe("Product Page", () => {
it("should display product details for ID 1", () => {
cy.visit("/products/1");
cy.contains("Product ID: 1");
});
});
Next.js has been rapidly evolving, and the latest advancements have made dynamic routing even more powerful:
Middleware allows for more advanced route handling, such as A/B testing, personalization, and redirection based on user behavior.
With on-demand ISR, you can regenerate specific dynamic routes without rebuilding the entire site, making it perfect for updating content in real-time.
Dynamic routing now benefits from React Server Components, reducing the need for client-side rendering and improving performance.
Mastering dynamic routes in Next.js unlocks immense potential for creating scalable, flexible, and SEO-friendly applications. Whether you’re building a blog, an e-commerce platform, or a social media site, Next.js dynamic routes provide the tools you need to handle complex, data-driven content effortlessly.
By following the steps outlined in this guide, you’ll be well-equipped to create dynamic routes that enhance the user experience, improve performance, and scale your application as it grows.
Prateeksha Web Design Company, an expert in digital solutions, offers services including a comprehensive guide on mastering dynamic routes in Next.js. This step-by-step program helps clients create impactful, flexible web applications with seamless navigation.
Interested in learning more? Contact us today.
Subscribe to our newsletter for exclusive offers and discounts on our packages. Receive bi-weekly updates from our blog for the latest news and insights.