Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
How To Get Current Route In Next.js?
Next article icon

How To Get Current Route In Next.js?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Next.js is a popular React framework that makes it easy to build server-side rendered and static web applications. One common task in web development is determining the current route or URL of the page. In Next.js, this can be done using the built-in useRouter hook. This article will guide you through the process of getting the current route in a Next.js application.

Prerequisites

  • React and React hooks
  • Next.js framework basics
  • JavaScript ES6 features

Table of Content

  • Method 1: Using useRouter() Method
  • Method 2: Using withRouter() Method
  • Method 3: Using getInitialProps() Method

Steps to Get Current Route in Next.js

Step 1: You can create a new NextJs project using the below command:

npx create-next-app gfg

Project Structure

Method 1: Using useRouter() Method

In NextJs we can easily get the value of the current route using the useRouter() function. To use this we are going to create a new page inside our pages directory with the name 'get-route.js'.

JavaScript
//get-route.js  import React from 'react' import {useRouter} from 'next/router';  export default function getRoute() {     // Calling useRouter() hook     const router = useRouter()     return (         <div>             <h1>GeeksforGeeks</h1>             <h2>pathname:- {router.pathname}</h2>             <h2>query:- {router.query}</h2>             <h2>asPath:- {router.asPath}</h2>         </div>     ) } 

Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output

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.

Knowing how to access the current route is essential for navigation and conditional rendering.

Method 2: Using withRouter() Method

You can easily get the current router value in react class component using the withRouter(). To use this you just have to export your class component inside withRouter(). In the below code first, we are importing our withRouter function from the next/router after that we are creating a new class component with the name of getRoute and inside that, In our render function, we are displaying the pathname, asPath, and query from the props received in our class. After that, we are exporting our class u=inside withRouter() function.

JavaScript
import React from 'react' import {withRouter} from 'next/router';  export class getRoute extends React.Component {          render() {         console.log(this.props.router.pathname)         console.log(this.props.router.query)         console.log(this.props.router.asPath)         return (             <div>                 <h1>GeeksforGeeks</h1>                 <h2>Using withRouter</h2>             </div>         )     } }  export default withRouter(getRoute) 

Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output

Method 3: Using getInitialProps() Method

You can also access the value of the route the context prop inside getInitialProps(). Context prop contains information of your routes like asPath, query, and Pathname. In the below code first, we are importing our withRouter function from the next/router after that we are creating a new class component with the name of getRoute and inside that, we are creating a async getIntitalProps function which contains context as a prop.

JavaScript
import React from 'react' import {withRouter} from 'next/router';  export class getRoute extends React.Component {      static async getInitialProps(context) {         // Using context prop to get asPath, query, context         const {asPath, query, pathname} = context          return{asPath, query, pathname}     }          render() {         // Consoling the values         console.log(this.props.pathname)         console.log(this.props.query)         console.log(this.props.asPath)         return (             <div>                 <h1>GeeksforGeeks</h1>                 <h2>Using Context prop in getInitialProps</h2>             </div>         )     } }  export default getRoute 

Step to run the application: Start the development server by typing the below command in the terminal.

npm run dev

Output


Next Article
How To Get Current Route In Next.js?

I

imranalam21510
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • Next.js

Similar Reads

    How to Get The Current URL Domain in Next.js ?
    In Next.js, we can get current url domain with the help of built-in methods like window and document location. In this article, we'll explore different approaches and best practices for obtaining the current URL domain in Next.js applications.The approaches to get the URL of the current domain in ne
    3 min read
    How to Catch All Routes in Next.js ?
    To catch all routes in Next.js, you create a dynamic route file using the catch-all segments syntax. This allows you to handle various routes dynamically, enhancing routing flexibility and application structure.Catch all routesTo catch all routes in next js, We willCreate a file named [...gfg].js in
    2 min read
    How to Get URL pathname in Next.js?
    Next.js is a powerful React framework that simplifies the process of building server-rendered and statically generated web applications. One common requirement in web development is to get the URL pathname, which can be useful for various purposes such as conditional rendering, routing, and analytic
    3 min read
    How to generate a route in Ember.js ?
    Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity.
    2 min read
    How to Disable the ETag Generation in Next.js ?
    ETags (Entity Tags) are a mechanism used by HTTP to validate the cache of resources and improve performance by avoiding unnecessary data transfers. In Next.js, ETags are generated by default for API routes to optimize caching. However, in some cases, you may need to disable ETag generation, such as
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences