Get URL pathname in Pages router

In pages router, [Tex]useRouter()[/Tex] hook is used to get pathname and slug of dynamic routes.

Example 1: Getting the pathname

JavaScript

//pages/pages-router/index.tsx import { useRouter } from "next/router"; export default function PagesRouter() { const router = useRouter(); return <div>Pages Router: {router.pathname}</div>; }

Output:

Example 2: Getting slug of a dynamic route.

A dynamic route is created by wrapping in square brackets: [segmentName]. For example [id], [slug]

JavaScript

//pages/pages-router/[slug]/index.tsx import { useRouter } from "next/router"; export default function PagesRouter() { const router = useRouter(); return <div>Pages Router Slug: {router.query.slug}</div>; }

Output:

Example 3: Getting the whole pathname of a dynamic Router

JavaScript

//pages/pages-router/[slug]/index.tsx import { useRouter } from "next/router"; export default function PagesRouter() { const router = useRouter(); return <div>Dynamic page: {router.asPath}</div>; }

Output:

How to Get URL pathname in Next.js?

Next.js is a React framework used to build sophisticated full-stack web applications. Since the introduction of the App router, Next.js’s popularity has skyrocketed, making it the most widely used React.js framework. When developing applications, we frequently require URL pathnames to enable different features for specific users.

In this article, we will explore how to obtain URL pathnames in Next.js applications.

Table of Content

  • What is an URL pathname
  • Get URL pathname in Pages router
  • Get URL pathname in App router
  • Conclusion

Prerequisites:

Similar Reads

What is an URL pathname?

According to MDN web docs “The pathname property of the URL interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a / character. If the URL has no path segments, the value of its pathname property will be the empty string.”...

Steps to Create NextJS Project

We will be using pnpm as the package manager and TypeScript, though you can use npm and JavaScript without any difference....

Get URL pathname in Pages router

In pages router, [Tex]useRouter()[/Tex] hook is used to get pathname and slug of dynamic routes....

Get URL pathname in App router

Client Component...

Conclusion

In this article we have learned how to setup what are URL pathname, how to setup Next.js project, how to get pathname in pages router and app router....

Contact Us