Parses URLSearchParams to JavaScript objects according to Zod schemas.
The set of allowed Zod schemas is restricted to ensure the parsing is unambiguous. This parser may be used as a true inverse operation to @seamapi/url-search-params-serializer.
By default, or when passing strict: true,
the parser only parses the expected output of @url-search-params-serializer,
making the parser a true inverse of the serializer:
- Parses
z.array()only in the repeated formatfoo=1&foo=2.- Array values may contain a
,and are never split, e.g.,foo=a,b&foo=cis parsed as['a,b', 'c']. - There is no bracket array format:
since the serializer never outputs it,
a param named
foo[]is unrelated to the paramfooand is parsed as a param literally namedfoo[].
- Array values may contain a
- For
z.boolean(), only the stringstrueandfalseare parsed. - Whitespace is significant and is never trimmed:
only a completely empty value is parsed as
null(or as the empty array forz.array()).
When passing strict: false, additional input cases are handled
at the cost of some limitations, e.g.,
array string values containing a , are not supported:
- For
z.number(),z.boolean(),z.date(),z.object(), andz.record(), whitespace only values are parsed asnull. - For
z.number(),z.boolean(),z.date(), starting and ending whitespace is trimmed before parsing. - For
z.boolean(), the following strings are parsed astrue:true,True,TRUE,yes,Yes,YES, and1. - For
z.boolean(), the following values are parsed asfalse:false,False,FALSE,no,No,NO, and0. - Parses
z.array()in the following formats. In order to support unambiguous parsing, array string values containing a,are not supported.foo=1&foo=2foo[]=1&foo[]=2foo=1,2
These rules apply in strict and generous mode alike:
- For
z.number(),z.boolean(), andz.date(), values that cannot be parsed as the expected type are passed through unchanged as strings, e.g.,foo=ais parsed as'a'forz.number(). Validating the parsed output is left to the schema. - For
z.string(), an empty value is parsed asnull, since the serializer treats the empty string asundefined. Whitespace is significant and is never trimmed forz.string(). - For
z.object()andz.record(), a non-empty value is passed through unchanged as a string, e.g.,foo=ais parsed as'a'. - Search params not present in the schema are ignored.
Some inputs are ambiguous and cannot be parsed unambiguously.
These throw an UnparseableSearchParamError:
- A non-array param with repeated values, e.g.,
foo=1&foo=2forz.number(). - An array param that mixes empty values with other values,
e.g.,
foo=&foo=1orfoo=&foo=. - An object or record param that conflicts with its own nested params,
e.g.,
foo.bar=&foo.bar.a=1, since this would be a null object containing a value. - A param nested inside a record param,
e.g.,
foo.a.b=1forz.record(z.string(), z.number()). - In generous mode (
strict: false):- An array param that mixes array formats,
e.g.,
foo=1&foo[]=2orfoo=1,2&foo=3. - An array param that repeats a value containing a
,, e.g.,foo=a,b&foo=c,d. - An array param using the bracket format with a value containing a
,, e.g.,foo[]=a,b. - An array param using the comma format with empty values,
e.g.,
foo=a,,b.
- An array param that mixes array formats,
e.g.,
Schemas that do not obey these rules throw an UnparseableSchemaError.
- The top-level schema must be an
z.object()orz.union()ofz.object(). - Properties may be a
z.object()orz.union()of objects. - All union object types must flatten to a parseable object schema with non-conflicting property types.
- Properties present in only some union options are parsed as optional.
- Using
z.discriminatedUnion()is allowed and equivalent toz.union().
- Primitive properties must be a
z.string(),z.number(),z.boolean()orz.date().- Properties must be a single-value type.
- The primitives
z.bigint()andz.symbol()are not supported. - Strings with zero length are not allowed.
If not specified, a
z.string()is always assumed to bez.string().min(1). - Using
z.enum()is allowed and equivalent toz.string(). - Using
z.nativeEnum()is allowed when all its values are strings or all its values are numbers.
- Any property may be
z.optional()orz.never(). - Any property may be
z.null(), which is always parsed asnull. - No property may
z.void(),z.undefined(),z.any(), orz.unknown(). - Any property may be
z.nullable()exceptz.array(). - Properties that are
z.literal()are allowed and must still obey all of these rules. - The
z.default()andz.readonly()wrappers are allowed and ignored. Defaults are not applied by this parser: applying them is left to the schema. - A
z.array()must be of a single value-type.- The value-types must obey all the same basic rules for primitive object, union, and property types.
- A union value-type must resolve to a single value-type,
e.g., a
z.union()ofz.literal()strings. - Value-types may not be
z.nullable()orz.undefined(). - The value-type cannot be a
z.object(). - The value-type cannot be an
z.array()or contain a nestedz.array()at any level. - The value-type cannot be a
z.boolean(). This restriction is not strictly necessary, but a deliberate choice not to support such schemas in this version.
- A
z.record()has less-strict schema constraints but weaker parsing guarantees:- They keys must be
z.string()or az.enum(). - The value-type may be a single primitive type.
- The value-type may be
z.nullable(). - The value-type may not be a
z.record(),z.array(), orz.object(). This restriction is not strictly necessary, but a deliberate choice not to support such schemas in this version. - The value-type may be a union of primitive types,
but this union must include
z.string()and all values will be parsed asz.string(). For schemas of this type, the parser is no longer a true inverse of the serialization.
- They keys must be
Add this as a dependency to your project using npm with
$ npm install @seamapi/url-search-params-parser
import { parseUrlSearchParams } from '@seamapi/url-search-params-parser'
parseUrlSearchParams(
'age=27&isAdmin=true&name=Dax&tags=cars&tags=planes',
z.object({
name: z.string().min(1),
age: z.number(),
isAdmin: z.boolean(),
tags: z.array(z.string()),
}),
) // => { name: 'Dax', age: 27, isAdmin: true, tags: ['cars', 'planes'] }Pass strict: false to enable generous parsing,
which accepts additional input formats
at the cost of no longer being a true inverse of the serializer.
parseUrlSearchParams(
'isAdmin=yes&tags=cars,planes',
z.object({
isAdmin: z.boolean(),
tags: z.array(z.string()),
}),
{ strict: false },
) // => { isAdmin: true, tags: ['cars', 'planes'] }This parser does not validate its output: pass the parsed params to the schema to both validate and type them.
const schema = z.object({ name: z.string().min(1), age: z.number() })
schema.parse(parseUrlSearchParams('age=27&name=Dax', schema))Parsing throws an UnparseableSchemaError when the schema is not supported,
and an UnparseableSearchParamError when the query string is ambiguous.
import {
parseUrlSearchParams,
UnparseableSchemaError,
UnparseableSearchParamError,
} from '@seamapi/url-search-params-parser'$ git clone https://github.com/seamapi/url-search-params-parser.git
$ cd url-search-params-parser
$ nvm install
$ npm install
$ npm run test:watch
Primary development tasks are defined under scripts in package.json
and available via npm run.
View them with
$ npm run
The source code is hosted on GitHub. Clone the project with
$ git clone git@github.com:seamapi/url-search-params-parser.git
You will need Node.js with npm and a Node.js debugging client.
Be sure that all commands run under the correct Node version, e.g., if using nvm, install the correct version with
$ nvm install
Set the active version for each shell session with
$ nvm use
Install the development dependencies with
$ npm install
New versions are released automatically with semantic-release as long as commits follow the Angular Commit Message Conventions.
Publish a new version by triggering a version workflow_dispatch on GitHub Actions.
The version input will be passed as the first argument to npm-version.
This may be done on the web or using the GitHub CLI with
$ gh workflow run version.yml --raw-field version=<version>
GitHub Actions should already be configured: this section is for reference only.
The following repository secrets must be set on GitHub Actions:
NPM_TOKEN: npm token for installing and publishing packages.GH_TOKEN: A personal access token for the bot user withpackages:writeandcontents:writepermission.GIT_USER_NAME: The GitHub bot user's real name.GIT_USER_EMAIL: The GitHub bot user's email.GPG_PRIVATE_KEY: The GitHub bot user's GPG private key.GPG_PASSPHRASE: The GitHub bot user's GPG passphrase.
If using squash merge, edit and ensure the commit message follows the Angular Commit Message Conventions specification. Otherwise, each individual commit must follow the Angular Commit Message Conventions specification.
- Create your feature branch (
git checkout -b my-new-feature). - Make changes.
- Commit your changes (
git commit -am 'Add some feature'). - Push to the branch (
git push origin my-new-feature). - Create a new draft pull request.
- Ensure all checks pass.
- Mark your pull request ready for review.
- Wait for the required approval from the code owners.
- Merge when ready.
This npm package is licensed under the MIT license.
This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.