Built-in parsers
When using strings is not enough
Search params are strings by default, but chances are your state is more complex than that.
You might want to use numbers, booleans, Dates, objects, arrays, or even custom types. This is where parsers come in.
nuqs
provides built-in parsers for the most common types, and allows you to define your own.
String
Type-safety tip
parseAsString
is a noop: it does not perform any validation when parsing,
and will accept any value.
If you’re expecting a certain set of string values, like 'foo' | 'bar'
,
see Literals for ensuring type-runtime safety.
If search params are strings by default, what’s the point of this “parser” ?
It becomes useful if you’re declaring a search params object, and/or you want to use the builder pattern to specify default values and options:
Numbers
Integers
Transforms the search param string into an integer with parseInt
(base 10).
Floating point
Same as integer, but uses parseFloat
under the hood.
Hexadecimal
Encodes integers in hexadecimal.
Going further
Check out the Hex Colors playground for a demo.
Boolean
Literals
These parsers extend the basic integer and float parsers, but test against some expected valid values, defined as TypeScript literals.
Note
Don’t forget the as const
when declaring your expected values.
String literals
Numeric literals
Enums
String enums are a bit more verbose than string literals, but nuqs
supports them.
Note
The query string value will be the value of the enum, not its name
(here: ?direction=UP
).
Dates & timestamps
There are two parsers that give you a Date
object, their difference is
on how they encode the value into the query string.
ISO 8601
Timestamp
Miliseconds since the Unix epoch.
Arrays
All of the parsers on this page can be used to parse arrays of their respective types.
JSON
If primitive types are not enough, you can encode JSON in the query string.
Pass it a validation function to validate and infer the type of the parsed data, like a Zod schema:
Using other validation libraries is possible, as long as they throw an error when the data is invalid (eg: Valibot, Yup, etc).
Using parsers server-side
You may import parsers from nuqs/server
to use them in your server code,
as it doesn’t include the 'use client'
directive.
Note
It used to be available under the alias import nuqs/parsers
,
which will be dropped in the next major version.