Express allows you to use either Node's built-in querystring module or the qs library for parsing query strings, as noted in the documentation. Let’s explore how we can send an array of values to them via query parameters.
Handling Repeated Query Parameters
You can repeat query parameters in the query string to produce an array on the server side. Both querystring and qs handle this use case effectively:
> querystring.parse('a=b&a=c')
[Object: null prototype] { a: [ 'b', 'c' ] }
> qs.parse('a=b&a=c')
{ a: [ 'b', 'c' ] }
Drawback
With this approach, you may end up with either an array (if the parameter is repeated) or a string (if the parameter appears only once):
> querystring.parse('a=b&a=c')
[Object: null prototype] { a: [ 'b', 'c' ] }
> querystring.parse('a=b')
[Object: null prototype] { a: 'b' }
Using Explicit qs Syntax for Arrays
The qs parser provides more explicit and reliable notations to ensure the result is always an array, even if there's only one value. These options include:
- Bracket Notation
> qs.parse('a[]=b&a[]=c')
{ a: [ 'b', 'c' ] }
- Index Notation
> qs.parse('a[1]=c&a[0]=b')
{ a: [ 'b', 'c' ] }
These notations are particularly useful because they guarantee an array is returned, even for a single value:
> qs.parse('a[]=b')
{ a: [ 'b' ] }
> qs.parse('a=b')
{ a: 'b' }
Drawback
These notations do not work with querystring:
> querystring.parse('a[]=b')
[Object: null prototype] { 'a[]': 'b' }
Summary
- Repeated Parameters: Work with both parsers but return an array only when the parameter is repeated.
qs Array Syntax: Guarantees an array but doesn’t work with querystring.
Documentation Insights
The official documentation is not very explicit about arrays of values in query strings. That is why we relied mostly in experimentation here. That said, it provides some relevant information here and there.
The Node.js querystring documentation includes an example showing repeated parameters result in an array:
For example, the query string 'foo=bar&abc=xyz&abc=123' is parsed into:
{
foo: 'bar',
abc: ['xyz', '123']
}
The qs documentation doesn’t explicitly mention repeated parameters for parsing but does confirm their behavior during stringification. In practice, repeated parameters work as expected:
> qs.parse('a=b&a=c')
{ a: [ 'b', 'c' ] }