Deviopath › Next.js

Multi-Value Filters in the URL

Hard · Search Params

Build product filters whose state lives only in the URL, so a filtered page can be shared, bookmarked and restored with the back button.

A URL can repeat a key: ?color=red&color=blue&size=m. Read all values with searchParams.getAll("color") and add one with params.append("color", "blue"). useSearchParams() returns a read-only object, so copy it first: new URLSearchParams(searchParams).

Render one checkbox per option: <input type="checkbox" name="color" value="red" /> for the colors red, blue, green, and name="size" for the sizes s, m, l. A checkbox is checked when its value is in the URL.

- Clicking a checkbox toggles only that value: add it with append (at the end) or remove just that value and keep the others. Update the URL with router.push. If no params are left, push the bare pathname (/, not /?).

- A product must match one of the selected colors (OR inside a group) and one of the selected sizes (AND across groups). A group with nothing selected does not filter.

- The URL may also contain q (set by a search box elsewhere). Products whose name does not contain q (case-insensitive) are hidden too.

- Values that are not options (like ?color=purple) are ignored: they filter nothing and check nothing.

- A Clear filters button removes all color and size params but keeps every other param (like q). It is disabled when no valid filter is selected.

- Show the matching names as <li> items in <ul className="results"> (original order) and the count in <p className="count">: 1 product, otherwise N products (also 0 products).

Next: Server Action CSRF Origin Check