human
human
TTCTheo's Typesafe Cult
Created by human on 5/4/2023 in #questions
Next.js 13 get current URL path in Server Component
This may be due to the current beta-phase of Next.js 13 app directory, but I am struggling to make a simple nav link with an active state based on the current path name–only with server components. I assumed that there were an API to get the current pathname, just like you can get headers and cookies in Server Components. But alas, I couldn't find any. I know this is possible to do with Client Components. But I wan't to keep the nav and its links server-side rendered for this example. The only alternative I can think of is kind of hacky; create a middleware that sets a header (or cookie) that is then read from that SC. I don't need these routes to be statically rendered anyway. I also tried to make a client-only provider component which would wrap around a nav link (rendered as a SC) and use tailwind's group feature, then use that group to set the nav link style based on the class name or state. This didn't work, however this resulted in the following error:
Error: usePathname only works in Client Components. Add the "use client" directive at the top of the file to use it.
Error: usePathname only works in Client Components. Add the "use client" directive at the top of the file to use it.
It seems that rendering a client component that uses useRouter or usePathname inside a server component isn't allowed (or supported), even if I don't wrap it (???) I am ok if I have to pass a prop from the layout into the main nav. That's not my main concern.
43 replies