Validating URL Query string in Node.js


A correctly formed query string looks like:


I want to map this “safely” into an object, but I don’t want to end up with undefined values. Is there a nice way of validating the query string?

Details: I want to turn this into an object with the url module. i.e.:

var url_parts = url.parse(request.url, true);

and then I can route based on url_parts.pathname. I want to access, and, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.

Problem courtesy of: YXD


set up defaults, and then overwrite them with values from your url.


var defaults = {
id : 0,
foo : 'default value',
bar : 'default.value'

var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.

Hope that helps!

Solution courtesy of: ehudokai

View additional discussion.