npm.io
0.0.3 • Published 12h ago

@1k/qs

Licence
MIT
Version
0.0.3
Deps
1
Size
7 kB
Vulns
0
Weekly
0

@1k/qs

Lightweight query string parse and stringify utilities with protection against prototype pollution and malformed URI sequences.

If you only need to read query parameters in a browser environment, consider the built-in URLSearchParams first.

Installation

npm install --save @1k/qs

Usage

import { parse, stringify } from '@1k/qs'
parse()

Parses a query string into a key-value object.

Parameters without values are set to empty strings. The leading ?, #, or no prefix are all handled transparently.

parse('foo=bar')          // { foo: 'bar' }
parse('?foo=bar')         // { foo: 'bar' }
parse('#foo=bar')         // { foo: 'bar' }
parse('foo=bar&bar=foo')  // { foo: 'bar', bar: 'foo' }
parse('foo&bar=foo')      // { foo: '', bar: 'foo' }
Duplicate keys

By default, duplicate keys are merged into arrays:

parse('a=1&a=2&a=3')  // { a: ['1', '2', '3'] }

Use { onlyFirst: true } to get the first value as a plain string instead:

parse('a=1&a=2&a=3', { onlyFirst: true })  // { a: '1' }
Decoding

+ is decoded as space (per application/x-www-form-urlencoded):

parse('key=a+b')  // { key: 'a b' }

Percent-encoded values are decoded via decodeURIComponent:

parse('key=%E4%B8%AD%E6%96%87')  // { key: '中文' }

Malformed URI sequences (e.g. %E) are returned as-is without throwing:

parse('key=%E&val=%GG')  // { key: '%E', val: '%GG' }
Custom decode
parse('key=hello', { decode: (s) => s.toUpperCase() })
// { key: 'HELLO' }
Prototype pollution protection

The returned object has no prototype chain (Object.create(null)), so keys like __proto__ or toString won't pollute global objects.

parse('__proto__[polluted]=true')  // safe — no prototype
stringify()

Serializes an object into a URL-encoded query string.

stringify({ foo: 'bar' })            // 'foo=bar'
stringify({ foo: 'bar', baz: 'qux' }) // 'foo=bar&baz=qux'
Prefix

Pass true or a custom string to add a prefix:

stringify({ foo: 'bar' }, true)  // '?foo=bar'
stringify({ foo: 'bar' }, '#')   // '#foo=bar'
stringify({ foo: 'bar' }, '&')   // '&foo=bar'
Edge cases
stringify({ a: null, b: NaN })        // 'a=&b='
stringify({ a: undefined })           // ''
stringify({})                          // ''

License

MIT

Keywords