Next.js Discord

Discord Forum

Access search params from arbitrary server component

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
👋 trying to see if there's a generic way to access search params from any server component. So far all I've encountered is the searchParams prop passed to top-level page components, but this requires some prop drilling down to server components which actually need it: https://nextjs.org/docs/app/api-reference/file-conventions/page#searchparams-optional

Might there be a module to import which would dynamically fetch these? I saw useSearchParams but that looks like a client-only hook. Maybe something similar to the cookies function?

19 Replies

Asiatic LionOP
hmm yeah, that's fair especially with regards to when server components should be invalidated. optimistically I would have hoped that a searchParams() helper could just throw for non-page cases, but I imagine that complicates things a fair bit.

prop drilling is probably fine for my particular case, but could createServerContext be used here as well? not sure if the API has been solidified / if there's a better solution for arbitrary component reads
Pacific sandlance
whats the name of this package?
server-only-context
Pacific sandlance
hmm, seems kinda useless based on what I read there but maybe I'm wrong once a layout is used anyway
why would that be?
Pacific sandlance
You can't rely on it
yeah its not as intuitive as you think
but its using cache() which is a solid solution imo
Pacific sandlance
I mean based on the folder structure you shold know where you are but yea you have to pass down from the known point
well back to our previous point, server component doesn't accurately know what route it is being rendered
furthermore, it doesn't make sense for a layout file to get the searchParams.
https://nextjs.org/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams
Certain components don't get rerendered if its the same route segment, thus creating possibility of params/data to become stale
@aardani furthermore, it doesn't make sense for a `layout` file to get the `searchParams`. https://nextjs.org/docs/app/api-reference/file-conventions/layout#layouts-do-not-receive-searchparams
Asiatic LionOP
yeah I agree! sorry should have clarified in my original post - I'm aware of the concerns around receiving page-level data like searchParams in layout components and wasn't targeting that case.

probably won't bother, but if I did go this route where would I theoretically set the initial context data? inline in the top-level page component render function?
I actually have no experience yet in using those and im already comfortable with just compositioning the elements so that it only pass props once