Get URL pathname in App router
Client Component
In client component [Tex]usePathname()[/Tex] hook is used to get pathname.
"use client";
import { usePathname } from "next/navigation";
const Page = () => {
const pathname = usePathname();
return <div>Current path: {pathname}</div>;
};
export default Page;
Output:
Server Component
Reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations. As server component renders on the server side, there is no window object from which we can get URL pathname. Other hacky solutions like [Tex]next/headers[/Tex] don’t work in Next 14 and is not recommended to use as it causes severe performance issues. If your logic need pathname then consider it moving to client component.
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