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
//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]
//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
//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
Contact Us