#Get the pathname using server side

1 messages · Page 1 of 1 (latest)

brave dome
#

I have a server component, how can I retrieve the pathname in this component?
That's because if I use usePathname I would have to change my component to client side... not good

autumn hatchBOT
#

Hi @brave dome. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

I'm sorry, but according to the information provided in the knowledge sources, it's not possible to directly access the pathname in a Server Component in Next.js. The usePathname hook is specifically designed for Client Components and cannot be used in Server Components.

This design is intentional to support layout state being preserved across page navigations and to allow for optimizations like caching and streaming. Reading the current URL from a Server Component is not supported in Next.js. This is because Server Components always render on the server, including for subsequent navigations, and any code that depends on pathname, which changes between navigation, would become stale.

However, there are workarounds discussed in the community, such as injecting the pathname into the request headers while it's still in the middleware, but these are not officially supported and may not work in all cases.

For more details, you can refer to the discussion on this topic in the Next.js GitHub issue (https://github.com/vercel/next.js/issues/43704).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: