#route details in server component
1 messages · Page 1 of 1 (latest)
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:
- Next.js Docs - App (https://nextjs.org/docs/app)
- Next.js Docs - usePathname (https://nextjs.org/docs/app/api-reference/functions/use-pathname)