Deviopath › Next.js

Filter and Sort with searchParams

Medium · Data Fetching

A page receives the URL query as the searchParams prop. Since Next.js 15 it is a **Promise**, so the page must be async and await it before reading values. Each value is a string, a string[] (when the key appears more than once, like ?tag=a&tag=b) or undefined.

The URL is user input, so a page must never trust it. Fall back to safe defaults on unknown values instead of crashing or showing an empty page.

Implement ProductsPage({ searchParams }). A real page would return JSX, but Server Components cannot render in this preview, so return the data the page would show: { category, sort, items }.

- category: the category param if it is one of CATEGORIES, otherwise "all" (no filter).

- sort: the sort param if it is one of SORTS, otherwise "name".

- If a param is an array, use its first value.

- items: the names of the matching products. "name" sorts A to Z (localeCompare); "price-asc" / "price-desc" sort by price, and products with the same price are ordered by name.

The driver renderProducts(query) is already written and passes searchParams as a Promise.

Next: generateStaticParams for Nested Segments