NextJS

Dynamic Routing in Next.js - A Step-by-Step Tutorial


Introduction to Dynamic Routing

Dynamic routing in Next.js allows you to create routes with variable segments, enabling you to build flexible and data-driven pages. In this tutorial, we'll walk through the steps of creating a dynamic route in Next.js.

Creating a Dynamic Route

1. Start by creating a new file in the `pages` directory. You can use brackets [ ] to indicate dynamic segments in your route. For example, create a file named [id].js:

                    // pages/post/[id].js
                    import { useRouter } from 'next/router';
                    function PostPage() {
                        const router = useRouter();
                        const { id } = router.query;
                        return (
                            <div>
                                <h1>Post {id}</h1>
                                <p>This is a dynamic route for post {id}.</p>
                            </div>
                        );
                    }
                    export default PostPage;
                

In this example, the value of id is dynamic and can change based on the URL segment.

2. Next, you can access the dynamic route by visiting URLs like /post/1 or /post/2, and the component will display the respective id value.

Linking to Dynamic Routes

Linking to dynamic routes in Next.js is straightforward. Use the Link component with dynamic parameters. For example:

                    import Link from 'next/link';
                    <Link href=`/post/[id]` as=`/post/1`>
                        <a>Post 1</a>
                    </Link>
                

In this code, clicking the `Post 1` link will take you to the dynamic route /post/1.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.