#route details in server component

1 messages · Page 1 of 1 (latest)

slim furnace
#

Is there a way I can know exactly what route or page the user is currently on in a server component?

I.e is there an equivalent to useLocation or usePathname on the server?

lean fossilBOT
#

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

#

In Next.js, by default, pages are Server Components and you can access the route segments through the params prop and the URL search params through the searchParams prop for a given page. However, reading the current URL from a Server Component is not supported. This design is intentional to support layout state being preserved across page navigations.

The usePathname hook, which lets you read the current URL's pathname, is a Client Component hook and intentionally requires using a Client Component. It's important to note that Client Components are not a de-optimization. They are an integral part of the Server Components architecture.

Here is an example of how you can use usePathname in a Client Component:

'use client'
 
import { usePathname } from 'next/navigation'
 
export default function ExampleClientComponent() {
 const pathname = usePathname()
 return <p>Current pathname: {pathname}</p>
}

For more complex routes, if you are using Client Components, you can use usePathname, useSelectedLayoutSegment, and useSelectedLayoutSegments.

Sources:


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