Next.js Discord

Discord Forum

How to access to nested query params objects

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hello,

I'm writing an endpoint in API routes to search all content in my site, however, in order to support multiple types of searchs, I need to allow a free "filters" object; for example, I need to proccess the next URL:

/api/search?type=product&itemsPerPage=10&page=2&filters[terms]=next&filters[price]=10000&filters[lang]=es

so, as you can see, the type, itemsPerPage and page params are accessible through the request.nextUrl.searchParams but the object filters cannot be accessed as others.

I tried with filter.terms and same problem; the only way I see to be able to send and receive this info successfully is to allow a json object in its value, like this example:

/api/search?type=product&itemsPerPage=10&page=2&filters={"terms":"next","price":10000,"lang":"es"}

however, this seems to be neither a standard nor natural nor a secure way of transferring data by this means (GET request).

Do you have any idea how I could solve this?

Thanks in advance.

3 Replies

Spectacled bearOP
mmmm @Ray the filters options are variable, for the example, and the type product it's ok, but for pages or articles this object needs another values and options, for example:

/api/search?type=page&itemsPerPage=10&page=2&filters[terms]=next&filters[parent]=/about-us&filters[date]=2024-01-10

I don't think that uses conditionals is a good solution, like:

let filters;
if (type === 'product') {
  filter = {
    terms: searchParams.get('terms'),
    price: searchParams.get('price'),
    lang: searchParams.get('lang')
  }
} else if (type === 'article') {
  filter = {
    terms: searchParams.get('terms'),
    parent: searchParams.get('parent'),
    date: searchParams.get('date')
  }
}


Thanks.