Getting pathname in server components (layout)
Unanswered
Giant panda posted this in #help-forum
Giant pandaOP
I noticed this question has been asked several times. From what I gather, this looks like the best method: https://www.propelauth.com/post/getting-url-in-next-server-components
However, since that was posted, it looks like
However, since that was posted, it looks like
headers()
is now async. That's fine, my layout.tsx component is async. I also added export const dynamic = 'force-dynamic'
to it. However, setting a x-pathname
header in my middleware.ts and attempting to retrieve it in layout.tsx with await headers()
always results in a null value. I'm not doing any fetch calls in between, so I'm a bit stumped what would prevent this header value from passing through. This is in local dev mode, and is reproducable doing local builds as well.4 Replies
Giant pandaOP
For what it's worth, using route groups looks like the best solution for my case, with the caveat that client-side transitions won't work across route groups:
app
├── (locale-group) // Route Group 1 (does not affect URL)
│ ├── [locale] // Dynamic locale segment
│ │ ├── layout.tsx // Layout 1: Has access to { locale }
│ │ └── page.tsx // Home page for a locale, e.g., /en
│
└── (slug-group) // Route Group 2 (does not affect URL)
├── [locale] // Dynamic locale segment (required for the path)
│ └── [...slug] // Catch-all slug segment
│ ├── layout.tsx // Layout 2: Has access to { locale, slug }
│ └── page.tsx // Slug page, e.g., /en/about
Asian black bear
One thing to keep in mind is that layouts typically don’t rerender which is why you cannot obtain the current path reliably in server-side code.
Hence why it’s recommended to rely on client-side hooks where possible
Giant pandaOP
If you go with a client-side solution, that means the path cannot be used in statically generated HTML? i.e., the DOM will be patched via Javascript after initial render?