![]() |
Next.js is a powerful React framework that simplifies the process of building server-rendered and statically generated web applications. One common requirement in web development is to get the URL pathname, which can be useful for various purposes such as conditional rendering, routing, and analytics. In this article, we will explore different methods to get the URL pathname in a Next.js application. Table of Content Prerequisites:What is an URL pathname?The URL pathname is the part of the URL that comes after the domain name, including the initial slash. For example, in the URL Steps to Get URL pathname in Next.jsWe will be using pnpm as the package manager and TypeScript, though you can use npm and JavaScript without any difference. Step 1: Create a next.js project using the following command. Navigate to desired directory and type the following command in terminal pnpm create next-app@latest ![]() Next.js Project Setup Folder structureGet URL pathname in Pages routerIn pages router, [Tex]useRouter()[/Tex] hook is used to get pathname and slug of dynamic routes. Example 1: Getting the pathname
OutputExample 2: Getting slug of a dynamic route. A dynamic route is created by wrapping in square brackets: [segmentName]. For example [id], [slug]
OutputExample 3: Getting the whole pathname of a dynamic Router
OutputGet URL pathname in App routerClient ComponentIn client component [Tex]usePathname()[/Tex] hook is used to get pathname.
OutputServer ComponentReading 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. ConclusionIn 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. |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 17 |