Next.js Discord

Discord Forum

How to access route segments in server components without prop-drilling?

Unanswered
Least Storm-Petrel posted this in #help-forum
Open in Discord
Avatar
Least Storm-PetrelOP
Is there a way to do this? I know that layout.tsx and page.tsx expose the route segments. But is there a way to access those in a nested tree?

The goal is to use something similar like in the Page router's getStaticProps. There, I could very easily pass down the route segments for my functions/components by using React's Context or Node's Async Store.

12 Replies

Avatar
European sprat
Aren't all the slugs available in params?
Avatar
Alfonsus Ardani
no
gSSP work because server logic is always at gSSP and never in a nested component.
with the addition of nested layouts in /app dir, there is not way for server components to reliably and accurately know the current path of where the server component is used.
you can
1. [use server context](https://github.com/manvalls/server-only-context)
2. use composition to prop drill once (this is what i recommend)
Avatar
Least Storm-PetrelOP
I naturally did something similar to 1.
However, I don't know what you mean regarding composition in 2. Do you have an example?
Avatar
Alfonsus Ardani
all of the server components are brought up to the top-level so any properties that you have can be directly prop drilled into the component
Image
Avatar
Least Storm-PetrelOP
Ah ok. Thanks!
Avatar
Alfonsus Ardani
and for context, Navbar is a client component so i couldnt use cache()
Avatar
Least Storm-PetrelOP
I think I'll use a simple server-context for the language (since the whole app is inside /[lang] and the middleware handles the redirects.) and do something different for other multi-level data. Probably some combination of prop-drilling, cache and using slots (react ones, not Next ones).
Avatar
Least Storm-PetrelOP
Thank you Alfon!
Avatar
Alfonsus Ardani
No problem! Good luck on your endeavor