Get pathname in server components
In client components,
usePathname
is available to get the current pathname. However, in server components, there is no such API. How do I get the pathname in server components?
You can easily use the params
prop of page components to retrieve the pathname at that particular page. You can then do prop drilling to pass this pathname to child server components. If you don't like prop drilling (me neither), use something like server-only-context
.
Do note though, as you might have already noticed, that it does not work everywhere. Specifically, if the component is a child of a page component, it should work, as the pathname can be reliably determined.
However, if you use it in a layout component, the pathname cannot be reliably determined. Since a layout is not recomputed when you navigate to a different page, it's only possible to get the pathname until that layout file; the pathname from that layout file onwards cannot be determined. In other words, if you have something like this
all server components inside layout.tsx
can only get the pathname until /users/[userId]
. It canot read appId
. You need to keep this in mind.
If you need to show certain elements on certain routes and not on other routes, or display certain element in different styling depending on the pathname, you need to use route groups or client components. In the above example, you can't ask layout.tsx
to display a banner for a particular appId
, if the layout is a server component.
See also: vercel/next.js#43704.