How do you get the current url in Nextjs?

Last updated

There are a couple ways to get the current url depending on if you need it in the browser or when you’re on the server.

Get the URL on the client side with a hook

You can get everything you need with the useRouter hook.

Import it like: import { useRouter } from 'next/router', then call it in your components render function, const router = useRouter(). You can now use the properties on router.

Let's take a look at an example based on the very page you're looking at right now!

Assuming the url of the page is /question/how-do-you-get-the-current-url-in-nextjs/, let's take a look at two common properties asPath and pathname.

import { useRouter } from 'next/router'

function QuestionPage() {
  const {
    asPath,        // the value: "/question/how-do-you-get-the-current-url-in-nextjs/"
    pathname,   // the value: "/question/[slug]"
  } = useRouter();

  return <h1>The Page</h1>

As you can see, router.asPath is the full path of the page. The pathname for this page, because it uses dynamic routing, contains the path parameter slug. If we wanted just the value of the slug, we can access it from router.query.slug.

Get the url on the server

If you need to get the URL when doing SSR i.e. getServerSideProps, you have a couple options. You could access it on the req that is passed in like req.url. This will give us the path just like before. An alternative is to use query, this object will contain query strings and path params. Finally, you'll see a resolvedUrl prop too. This is the url without the _next/data prefix for client transitions.

export async function getServerSideProps({ req, query, resolvedUrl }) {
  console.log(req, query, resolvedUrl)
  return { props: {} }

Take a look at the Next.js docs for getServerSideProps for all the available properties on context.

Static site generation and the url

If you're using SSG on your Next.js site, i.e. using getStaticProps, then you'll have access to params which is an object containing the parameters defined by the path as well as useRouter like before.

So the following on the question page would log { slug: 'how-do-you-get-the-current-url-in-nextjs' } to the console when building the page :

export async function getStaticProps({ params }) {
  return { props: {} }

These are the most common properties and techniques for getting the URL in Next.js. If you're working with internationalisation, you can also access locale to determine which locale is active.

Seth Corker

A Fullstack Software Engineer working with React and Django. My main focus is JavaScript specialising in frontend UI with React. I like to explore different frameworks and technologies in my spare time. Learning languages (programming and real life) is a blast.