Open In App

Next.js Dynamic Route Segments

Last Updated : 05 Jan, 2023
Like Article

In this article, we will learn How we can get the current route in our NextJS project.

NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.

Dynamic route segments are dynamic routes (a.k.a. url slugs, pretty urls, and others) that we can create in NextJs apps using the brackets in the name of the file. This will help developers to create more complex apps which will be difficult to create only with predefined paths.

Create NextJS Application: You can create a new NextJs project using the below command:

npx create-next-app gfg

Project Structure: It will look like this.

NextJs allows the feature to create dynamic routes without much effort. You can follow the below steps to create dynamic routes.

Step 1: Create a new folder with the name of ‘dynamic’ and inside that folder create a dynamic route. We can create dynamic routes in NextJs by using square brackets in the name of the file. For example:-


Step 2: Create a dynamic route file with the name ‘[data] .js‘ and add the below content in the file.


import React from 'react'
import {useRouter} from 'next/router';
export default function getRoute() {
    // Calling useRouter() hook
    const router = useRouter()
    return (
            <h2>pathname:- {router.pathname}</h2>
            <h2>asPath:- {router.asPath}</h2>

In the above example first, we are calling our useRouter() hook and after that, we are displaying the objects of our router in the console.

  • pathname:  Current route. That is the path of the page in ‘/pages’.
  • query: The query string parsed to an object.
  • asPath: The path (including the query) shown in the browser.

Step 3: Start the development server by typing the below command in the terminal.

npm run dev


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads