bhylu.com

Advertisements

Node.js Query Parameters

URLSearchParams parses query fields as strings and can contain repeated keys. Decide whether repetition is valid instead of silently accepting an arbitrary first or last value.

How it works

A limit parameter should have a small explicit range and a default policy. SQL identifiers or expression text should not be accepted merely because a number was validated elsewhere. This fixture rejects repeated limit values and non-decimal input before constructing a numeric result. It parses fixed URL fixtures only, allowing the rule to be tested without starting a server for every individual parser case.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as query-parameters.mjs in a separate empty exercises folder and run node query-parameters.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

query-parameters.mjs

function pageLimit(url) {
  const values = url.searchParams.getAll('limit');
  if (values.length === 0) return 10;
  if (values.length !== 1 || !/^[1-9][0-9]?$/.test(values[0]))
    throw new Error('Invalid limit');
  const limit = Number(values[0]);
  if (limit > 20) throw new Error('Invalid limit');
  return limit;
}
console.log(pageLimit(new URL('http://desk.invalid/kits?limit=2')));
try {
  pageLimit(new URL('http://desk.invalid/kits?limit=2&limit=3'));
} catch (error) {
  console.log(error.message);
}

Expected result

2
Invalid limit

The parser produces a bounded integer and rejects an ambiguous repeated parameter. A server can translate that known rejection into a client status while unexpected exceptions retain their separate internal-failure path.

Use the Node.js API reference for the precise version contract.