Get URL pathname in nextjs

Solution 1:

If you want to access the router object inside any functional component in your app, you can use the useRouter hook, here's how to use it:

import { useRouter } from 'next/router'

export default function ActiveLink({ children, href }) {
  const router = useRouter()
  const style = {
    marginRight: 10,
    color: router.pathname === href ? 'red' : 'black',
  }

  const handleClick = e => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick} style={style}>
      {children}
    </a>
  )
}

If useRouter is not the best fit for you, withRouter can also add the same router object to any component, here's how to use it:

import { withRouter } from 'next/router'

function Page({ router }) {
  return <p>{router.pathname}</p>
}

export default withRouter(Page)

https://nextjs.org/docs/api-reference/next/router#userouter

Solution 2:

You can use asPath property, that will give you the path (including the query) shown in the browser without the configured basePath or locale:

const { asPath } = useRouter()

Solution 3:

Suppose the complete URL of a page is 'abc.com/blog/xyz' and the component file name matching with this route is './pages/blog/[slug].js'

useRouter() hook returns a route object, which has two properties to get the pathname.

  1. One is asPath property, and

  2. Another one is pathname property.

asPath property contains pathname extracted from the URL i.e. /blog/xyz

but pathname property contains the pathname of your project directory i.e. /blog/[slug].

Example Implementation

// .pages/blog/[slug].js

import { useRouter } from 'next/router';

const BlogSlug = () => {
  const { asPath, pathname } = useRouter();
  console.log(asPath); // '/blog/xyz'
  console.log(pathname); // '/blog/[slug]'
  return (
    <div></div>
  );
}

export default BlogSlug;