Codementor Events

Building a Dynamic Routing Application in Next.js

Published Dec 19, 2024

Next.js is one of the most popular frameworks for building server-rendered React applications. It’s known for its simplicity, performance, and powerful features such as file-based routing, API routes, and server-side rendering (SSR). In this article, we’ll explore dynamic routing in Next.js and learn how to create a flexible application that can handle varying URL structures efficiently.

What is Dynamic Routing?

Dynamic routing refers to the ability to define routes that change based on the parameters provided in the URL. For example, instead of creating separate static pages for each blog post like /post1 and /post2, you can use dynamic routing to create a single page, /post/[id], where id can be any value.

This approach reduces redundancy, improves scalability, and makes the application easier to maintain.

Setting Up the Project

To get started, let’s create a Next.js application:

npx create-next-app@latest dynamic-routing-example
cd dynamic-routing-example
npm run dev

This sets up a basic Next.js project with a development server running at http://localhost:3000.

File-Based Routing in Next.js

Next.js uses a file-based routing system where files inside the pages directory automatically become routes. For example:

pages/index.js → /

pages/about.js → /about

To implement dynamic routing, we use square brackets in the file name.

Creating a Dynamic Route

Suppose you’re building a blog. Each post has a unique identifier (e.g., id). To create a dynamic route for individual blog posts:

1. Create a Dynamic File:

Inside the pages directory, create a new folder called post and add a file named [id].js:

mkdir pages/post
touch pages/post/[id].js

2. Add Dynamic Content:

Open pages/post/[id].js and add the following code:

import { useRouter } from 'next/router';

const Post = () => {
    const router = useRouter();
    const { id } = router.query;

    return (
        <div>
            <h1>Post ID: {id}</h1>
            <p>This is the content of post {id}.</p>
        </div>
    );
};

export default Post;

Here, useRouter is a Next.js hook that provides access to the router object, allowing us to retrieve the id parameter from the URL.

  1. Test the Route:

Start the development server (npm run dev) and navigate to http://localhost:3000/post/1. You’ll see the content for post 1. Change 1 to any other value in the URL to see it update dynamically.

Fetching Data for Dynamic Routes

In real-world applications, dynamic routes often require fetching data from an API or database. Next.js provides a method called getStaticProps for static generation and getServerSideProps for server-side rendering.

Example: Static Generation

Let’s fetch data for each post during build time using getStaticProps and getStaticPaths:

1. Define Paths:

export async function getStaticPaths() {
    const paths = [
        { params: { id: '1' } },
        { params: { id: '2' } },
        { params: { id: '3' } },
    ];

    return { paths, fallback: false };
}

Here, paths specifies the routes to pre-render at build time. Each params object corresponds to a dynamic segment.

2. Fetch Data:

Use getStaticProps to fetch data for each route:

export async function getStaticProps({ params }) {
    const { id } = params;
    const postData = { id, content: `This is the content for post ${id}.` };

    return { props: { postData } };
}

const Post = ({ postData }) => (
    <div>
        <h1>Post ID: {postData.id}</h1>
        <p>{postData.content}</p>
    </div>
);

export default Post;

The postData object is passed as a prop to the Post component.

3. Test the Application:

Restart the development server and navigate to http://localhost:3000/post/1. You’ll see the pre-rendered content.

Adding a Fallback

Sometimes, you might not want to pre-render all routes. Using fallback: true in getStaticPaths, you can dynamically generate pages on request. Here’s how:

export async function getStaticPaths() {
    return { paths: [], fallback: true };
}

export async function getStaticProps({ params }) {
    const { id } = params;
    const postData = await fetchPostData(id); // Replace with your data fetching logic

    return { props: { postData } };
}

const Post = ({ postData }) => (
    <div>
        <h1>Post ID: {postData.id}</h1>
        <p>{postData.content}</p>
    </div>
);

export default Post;

If a page doesn’t exist during the build, Next.js will generate it on the fly and cache it for subsequent requests.

Conclusion

Dynamic routing in Next.js is a powerful feature that simplifies creating flexible and scalable applications. With tools like getStaticPaths and getStaticProps, you can efficiently handle data-driven pages and optimize performance. Whether you’re building a blog, e-commerce site, or dashboard, dynamic routing can help you deliver a seamless user experience.

Happy coding!

Follow Me for more interested Article

Visit my blogs website

Support me on Patreon

I would love to see you in my followers list.

Discover and read more posts from Riza
get started