Next.js Discord

Discord Forum

Manipulate Search Params type in Server Components

Unanswered
Bombay posted this in #help-forum
Open in Discord
BombayOP
Can I change the searchParams type that arrive at the page level of a server components through middleware or else?

Problem: I use nested searchParams. lile ?sorting[key]=name&sorting[order]=asc

In nextjs these searchParams arrive as { 'sorting[key]': 'name', and 'sorting[orinder]': 'asc' } at the page. I have to use qs.parse to get them back.

Can I move the parsing to a middleware so that every page receives searchParams that are already parsed back?

3 Replies

Yes you can do that by reading the search params in middleware and saving it to header()
Then at server component you can simply get header().get('sorting[key]')
its not going to be typed. if you need typing, might want to use client component and check out nuqs insetad