Skip to main content
You may wish to customise the rendered query string for your data type. For this, nuqs exposes the createParser{:ts} function to make your own parsers.

Creating a parser

You pass createParser{:ts} two required functions:
  1. parse{:ts}: a function that takes a string and returns the parsed value, or null{:ts} if invalid.
  2. serialize{:ts}: a function that takes the parsed value and returns a string.
The parse{:ts} function should always return null{:ts} for invalid inputs. Never throw an error from the parse function.

Hex color parser example

Here’s a practical example of a parser that handles hex color values:

Equality function

For state types that can’t be compared by the ==={:ts} operator, you’ll need to provide an eq{:ts} function as well:
This is used for the clearOnDefault{:ts} option, to check if the current value is equal to the default value.

Multi Parsers

The parsers we’ve seen until now are SingleParsers{:ts}: they operate on the first occurence of the key in the URL, and give you a string value to parse when it’s available. MultiParsers{:ts} work similar to SingleParsers{:ts}, except that they operate on arrays, to support key repetition:
This means:
  1. parse{:ts} takes an Array<string>{:ts}. It receives all matching values of the key it operates on, and returns the parsed value, or null{:ts} if invalid.
  2. serialize{:ts} takes the parsed value and returns an Array<string>{:ts}, where each item will be separately added to the URL.
You can then compose & reduce this array to form complex data types:

Builder pattern

Parsers created with createParser{:ts} have access to the builder pattern, allowing you to chain configuration methods:

Testing custom parsers

Parsers should be bijective: parse(serialize(x)) === x{:ts} and serialize(parse(x)) === x{:ts}. To help test bijectivity, you can use helpers defined in nuqs/testing:

Lossy serializers

If your serializer loses precision or doesn’t accurately represent the underlying state value, you will lose this precision when reloading the page or restoring state from the URL (eg: on navigation).Example:
Here, setting a latitude of 1.23456789 will render a URL query string of lat=1.2345, while the internal lat state will be correctly set to 1.23456789.Upon reloading the page, the state will be incorrectly set to 1.2345.