Deviopath › Next.js

Typed searchParams with a Schema

Hard · Search Params

In Next.js 16 a page receives searchParams as a Promise of a plain object: { [key: string]: string | string[] | undefined }. A key that appears several times (?tags=a&tags=b) becomes an array. Everything is a string and anyone can edit the URL, so pages usually parse it with a schema (libraries like Zod or nuqs do this). Write that parser by hand.

parseFilters(searchParams) awaits the Promise and returns { filters, warnings }. The fields, in this order:

- q (string): trimmed. Default "".

- page (number): digits only and >= 1. Default 1.

- minPrice (number or null): digits with optional decimals like 12.50, no sign. Default null.

- inStock (boolean): true or 1 means true, false or 0 means false. Default false.

- tags (string[]): see below. Default [].

- sort: one of relevance, price-asc, price-desc, newest. Default relevance.

Rules:

- For single-value keys, an array means "use the first value". A missing key or an empty string silently gives the default.

- An invalid value gives the default and adds the warning <key>: "<raw value>" is not a valid value. Warnings follow the field order above. Unknown keys are ignored.

- tags accepts one string or an array; every value is split on commas, trimmed and lowercased; empty parts and repeats are dropped (first occurrence wins). Tags never produce warnings.

toSearchString(filters) builds the canonical query string so equal filters always give the same URL (good for caching and SEO): keys in the field order above, values equal to the default left out, inStock written as true, one tags param per tag, encoded with URLSearchParams. Return "" when everything is default, otherwise "?" plus the params.

Next: Resolve Metadata Across Layouts