Skip to main content

Parser Architecture

Parsers in nuqs are the foundation of type-safe URL state synchronization. They define how values are converted between URL query strings (always strings) and typed application state.

Core Interfaces

SingleParser

The SingleParser interface handles single-value query parameters:
From: packages/nuqs/src/parsers.ts:7-32
'single'
Parser type identifier. Defaults to 'single' if not specified.
(value: string) => T | null
required
Converts a URL query string value to the typed state value.Must return null for invalid inputs rather than throwing errors. This ensures graceful degradation when URLs contain unexpected values.
(value: T) => string
Converts the typed state value back to a URL query string.Must be lossless - parsing a serialized value should return the original value.Defaults to String if not provided.
(a: T, b: T) => boolean
Custom equality function for comparing state values.Used with clearOnDefault to determine when to remove the query parameter from the URL.Defaults to referential equality (a === b) if not provided. Essential for objects and arrays.

MultiParser

The MultiParser interface handles array-based query parameters (e.g., ?tag=react&tag=next):
From: packages/nuqs/src/parsers.ts:34-39
'multi'
required
Must be set to 'multi' to handle multiple values for the same key.
(value: ReadonlyArray<string>) => T | null
required
Parses an array of query string values. Each value comes from a repeated parameter (e.g., ?id=1&id=2&id=3).
(value: T) => Array<string>
Serializes the state value into an array of query string values.
(a: T, b: T) => boolean
Custom equality function for comparing state values.

Builder Pattern

All parsers created with createParser implement the builder pattern for configuration:

SingleParserBuilder

From: packages/nuqs/src/parsers.ts:52-123

MultiParserBuilder

From: packages/nuqs/src/parsers.ts:125-144

Type Inference

Extract TypeScript types from parsers using the inferParserType helper:
From: packages/nuqs/src/parsers.ts:583-588

Design Principles

1. Always Return Null for Invalid Input

Parsers should gracefully handle invalid input by returning null, never throwing errors:

2. Lossless Serialization

Serializers must be lossless to prevent data corruption on page reload:
From: packages/nuqs/src/parsers.ts:262-268

3. Provide Custom Equality for Objects

When parsing objects or arrays, provide a custom eq function:
From: packages/nuqs/src/parsers.ts:452-455

Next Steps