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

PHASE 1 — Topic 4: How Socket.IO Works Internally (Engine.IO, Transports, and Fallback)

We now understand what Socket.IO is and why it is useful. In this post, we go one level deeper and look at what actually happens behind the ...