Dynamic Routing in Next Js (Slug Implement)

To implement slug URLs in Next.js, you can follow these steps:

Step 1: Set up a Next.js project

  • Make sure you have a Next.js project set up. You can create a new Next.js project using the following command:


    npx create-next-app my-app

Step 2: Create a dynamic page

  • Next, create a dynamic page that will use the slug URL. In this example, we'll create a page to display a blog post based on its slug.
Here is the example to implement dynamic routing based file structure:

To get slug in src/app/contact/[slug]/page.js file, write this code:


    "use client"
    const BlogPost = ({ params }) => {
        const { slug } = params

        return (
            <div>
                <p>Slug: {slug}</p>
            </div>
        );
    };

    export default BlogPost;

Sample Slug Urls:

  • http://localhost:3000/contact/get-post
  • http://localhost:3000/contact/post-post
  • http://localhost:3000/contact/fetch-post

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...