Course outline

Node.js / Basic: the Node.js runtime / Lesson 7

Parse URLs and validate query parameters

Use Node’s URL API to separate URL structure from query data and validate a bounded numeric parameter.

About 18 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Read a URL without manually splitting encoded query text.
  • Validate a query parameter before use.
  • Distinguish missing, invalid, and valid inputs.
  • Parse URL structure and validate a required limit without implicit coercion.
  • Handle duplicates, encoding, and invalid effects under an explicit policy.

Identify the input boundary

A URL combines a path, optional query parameters, and other components. The query is external input even when the route itself is known. Decide whether a parameter is required, whether repeated parameters are allowed, and what values are valid before using it in application logic. This example requires a decimal limit from 1 through 100. A missing or invalid limit is rejected rather than quietly becoming an unlimited query.

Parse structure before interpreting values

The URL API separates the path from search parameters and decodes the query value for the caller. The example uses a synthetic absolute URL and reads q and limit independently. get returns the first matching value or null when absent; a service that forbids duplicates should inspect all values and reject more than one. Do not split the raw query on ampersands and assume encoded characters have the same meaning as separators.

javascript Read a synthetic URL
const url = new URL("https://example.test/search?q=red%20apple&limit=3");
console.log(url.pathname);
console.log(url.searchParams.get("q"));
console.log(url.searchParams.get("limit"));

URL and searchParams expose the parsed path and decoded query values.

Apply a domain rule

The parser below accepts a nonempty string of decimal digits, converts it to a number, and checks both integer safety and the allowed range. It rejects null, zero, fractions, signs, and values outside the stated limit. It intentionally returns null on failure, so the caller must branch before using the value. If a product permits leading zeroes or a default for missing input, state that behavior explicitly and test it.

javascript Validate the limit
function parseLimit(text) {
  if (text === null || !/^\d+$/.test(text)) return null;
  const value = Number(text);
  return Number.isSafeInteger(value) && value >= 1 && value <= 100 ? value : null;
}
console.log(parseLimit("3"));
console.log(parseLimit("0"));

The regular expression and range checks establish the stated integer contract.

Keep parsing and effects separate

An HTTP handler can parse and validate before opening a database query or making a remote request. On rejection it should send the documented client error and avoid the effect. A safe integer within 1–100 bounds the requested count, but it does not authorize access to the records or make a database query safe by itself. Authorization and parameterized data access remain separate responsibilities.

Verify boundaries and duplicates

Test a valid limit, the minimum and maximum, zero, 101, a fraction, an empty value, missing input, and repeated limit parameters. Check percent-encoded search text and confirm that the handler reports invalid input without executing its dependency. Run the examples with a supported Node installation; the second block is independent of the first. Record expected behavior for each case so future changes cannot silently expand the accepted range.

Parse request structure before values

A request target can contain a pathname and a query string. Parse it with URL and a deliberate fixed base, then route on the method and pathname while reading query values through searchParams. For GET /items?limit=3, pathname is /items and the limit value is the string "3". Comparing the raw target to /items would incorrectly reject a query-bearing request. Parsing identifies structure; it does not decide whether a value is valid or whether the requester is authorized.

Use a base appropriate to the server's request-target contract and handle malformed targets according to that contract. Do not trust a Host header as an authorization decision. Query parameters may be absent, empty, repeated, or encoded. Decide the policy for each before performing a data query. The examples use synthetic local inputs under Node 22.23.3 and do not access a real database.

Validate the complete limit representation

The lesson's example limit is required, written as decimal digits, and must convert to a safe integer from 1 through 100 inclusive. The original query value is text. Reject absence and empty text, check the entire digit representation, convert with Number, and then check Number.isSafeInteger and the inclusive range. Under this policy "3" yields numeric 3; "0" is a range failure; "101" exceeds the upper bound. A malformed value such as "3x" is not made valid by parseInt returning a prefix.

Document whether leading zeroes and whitespace are allowed. A digits-only policy can accept "003" as numeric 3 if the product permits it; it rejects a literal space unless normalization is a separate documented step. Number accepts representations beyond that grammar, so conversion success is not a substitute for the format check. Keep a structured error category or another documented failure outcome rather than silently choosing a default for a required value.

Choose an explicit duplicate policy

URLSearchParams can contain the same key more than once. get returns one value, while getAll exposes all values in their order. If the application requires exactly one limit, reject zero or multiple occurrences before interpreting the value; do not accidentally make first-wins behavior a security or business rule. If repeats are intentionally supported, define how each value is validated and combined.

Encoding is also part of the representation. URLSearchParams decodes percent-encoded values and treats plus signs according to query encoding rules. Validate the decoded value that the application will use, and test the actual target rather than assuming the raw bytes are the final number. A valid limit does not establish permission to access the requested data; authorization remains a separate trusted boundary.

Keep validation ahead of effects

A route handler should not execute its database or report query until the target, parameter count, syntax, and domain checks have succeeded. Return the documented client error for an invalid limit, then return from the handler so a success branch cannot run. Different failures such as missing and out-of-range values may share an HTTP status but can retain distinct safe categories for diagnostics or user feedback. Do not include secrets or raw private request data in logs.

Keep the parser pure when practical: accept a string or list of values and return a number or structured error, leaving HTTP response writing to an adapter. Test the parser directly with synthetic values and test the handler separately with a recording query fake. For a rejected limit, assert that the fake receives zero calls. A type annotation or URL parse alone cannot enforce the business rule.

Test duplicates and boundaries

Create a table covering a missing parameter, empty text, one and one hundred, zero and one hundred one, a fractional string, a suffix, an unsafe digit string, and duplicates. Include the allowed leading-zero and encoding cases only if they match the documented policy. Assert the exact numeric result or error category and ensure invalid inputs do not trigger the query. A successful parse of one representation does not prove the application is authorized to return the data.

The local examples run as complete .mjs scripts under Node 22.23.3 using synthetic targets and no network connection. The public renderer displays them without execution. A local test is evidence for the stated policy and host; actual HTTP parsing, authorization, resource limits, and deployment configuration require separate integration evidence.

20 worked examples

1. Parse pathname

Problem: Separate the path from a limit query in a synthetic target.

  1. The URL parser separates pathname from the query string.
  2. Routing can match /items while preserving the separate limit parameter.
javascript Parse pathname
const u = new URL("/items?limit=3", "http://localhost"); console.log(u.pathname);
Expected output
/items

Why this result follows: Routing can match /items while preserving the separate limit parameter.

2. Read limit text

Problem: Inspect the runtime type of a query parameter before conversion.

  1. URLSearchParams returns the supplied parameter as text.
  2. The original value remains a string until an explicit conversion occurs.
javascript Read limit text
const u = new URL("/items?limit=3", "http://localhost"); const x = u.searchParams.get("limit"); console.log(x, typeof x);
Expected output
3 string

Why this result follows: The original value remains a string until an explicit conversion occurs.

3. Missing limit

Problem: Observe the result when a required query key is absent.

  1. The target has no limit query parameter.
  2. The parser returns null, allowing the handler to report a missing value.
javascript Missing limit
const u = new URL("/items", "http://localhost"); console.log(u.searchParams.get("limit"));
Expected output
null

Why this result follows: The parser returns null, allowing the handler to report a missing value.

4. Empty limit

Problem: Distinguish a present empty limit from an absent parameter.

  1. The key is present but its value contains no characters.
  2. The empty string is a format failure under the required digit policy.
javascript Empty limit
const u = new URL("/items?limit=", "http://localhost"); console.log(JSON.stringify(u.searchParams.get("limit")));
Expected output
""

Why this result follows: The empty string is a format failure under the required digit policy.

5. Valid limit three

Problem: Convert the digit text three and check the stated range.

  1. The text contains digits and converts to safe integer three.
  2. Three lies inside the inclusive one-to-one-hundred domain.
javascript Valid limit three
const text = "3"; const n = Number(text); console.log(/^\d+$/.test(text) && Number.isSafeInteger(n) && n >= 1 && n <= 100 ? n : "invalid");
Expected output
3

Why this result follows: Three lies inside the inclusive one-to-one-hundred domain.

6. Lower limit boundary

Problem: Accept the lower inclusive limit boundary of one.

  1. One is a safe integer at the stated lower boundary.
  2. The inclusive comparison accepts the smallest permitted limit.
javascript Lower limit boundary
const n = Number("1"); console.log(Number.isSafeInteger(n) && n >= 1 && n <= 100);
Expected output
true

Why this result follows: The inclusive comparison accepts the smallest permitted limit.

7. Upper limit boundary

Problem: Accept the upper inclusive limit boundary of one hundred.

  1. One hundred is a safe integer at the maximum.
  2. The upper comparison includes the exact endpoint of the allowed range.
javascript Upper limit boundary
const n = Number("100"); console.log(Number.isSafeInteger(n) && n >= 1 && n <= 100);
Expected output
true

Why this result follows: The upper comparison includes the exact endpoint of the allowed range.

8. Reject zero

Problem: Reject zero under the positive limit range.

  1. Zero is an integer but is below the minimum one.
  2. The range check rejects zero rather than treating it as a missing key.
javascript Reject zero
const n = Number("0"); console.log(Number.isSafeInteger(n) && n >= 1 && n <= 100);
Expected output
false

Why this result follows: The range check rejects zero rather than treating it as a missing key.

9. Reject above maximum

Problem: Reject 101 as the first integer above the maximum.

  1. One hundred one exceeds the maximum one hundred.
  2. The upper-bound condition rejects this immediate outside neighbor.
javascript Reject above maximum
const n = Number("101"); console.log(Number.isSafeInteger(n) && n >= 1 && n <= 100);
Expected output
false

Why this result follows: The upper-bound condition rejects this immediate outside neighbor.

10. Reject suffix

Problem: Reject a limit string containing digits followed by a letter.

  1. The anchored grammar requires every character to be a digit.
  2. The suffix makes the complete representation invalid before conversion.
javascript Reject suffix
const text = "3x"; console.log(/^\d+$/.test(text));
Expected output
false

Why this result follows: The suffix makes the complete representation invalid before conversion.

11. Reject fractional text

Problem: Reject decimal text under the stated digits-only limit policy.

  1. The decimal point is not permitted by the selected grammar.
  2. The format check rejects the fraction before numeric range evaluation.
javascript Reject fractional text
const text = "2.5"; console.log(/^\d+$/.test(text));
Expected output
false

Why this result follows: The format check rejects the fraction before numeric range evaluation.

12. Leading zeroes

Problem: Accept leading zeroes when the digit policy explicitly permits them.

  1. All characters are digits and the conversion gives numeric three.
  2. Under this stated policy the leading zeroes do not make the representation invalid.
javascript Leading zeroes
const text = "003"; const n = Number(text); console.log(/^\d+$/.test(text), n);
Expected output
true 3

Why this result follows: Under this stated policy the leading zeroes do not make the representation invalid.

13. Unsafe digit string

Problem: Reject a digit string beyond safe integer precision.

  1. The converted number exceeds the maximum safe integer.
  2. The safety check rejects it even though its characters are all digits.
javascript Unsafe digit string
const n = Number("9007199254740992"); console.log(Number.isSafeInteger(n));
Expected output
false

Why this result follows: The safety check rejects it even though its characters are all digits.

14. Duplicate limit

Problem: Inspect all values for a repeated limit parameter.

  1. The query contains two occurrences in the stated order.
  2. getAll exposes both values so a single-value policy can reject duplicates.
javascript Duplicate limit
const u = new URL("/items?limit=3&limit=4", "http://localhost"); console.log(JSON.stringify(u.searchParams.getAll("limit")));
Expected output
["3","4"]

Why this result follows: getAll exposes both values so a single-value policy can reject duplicates.

15. Single-value policy

Problem: Reject repeated limit values before choosing a number.

  1. The query supplies two values for the same key.
  2. The explicit count check rejects ambiguity under the one-value contract.
javascript Single-value policy
const u = new URL("/items?limit=3&limit=4", "http://localhost"); console.log(u.searchParams.getAll("limit").length === 1 ? "single" : "duplicate");
Expected output
duplicate

Why this result follows: The explicit count check rejects ambiguity under the one-value contract.

16. First value only

Problem: Observe get on a repeated query key without treating it as a policy.

  1. get returns the first value for this repeated key.
  2. A one-value contract must still inspect duplicates rather than silently accepting first-wins.
javascript First value only
const u = new URL("/items?limit=3&limit=4", "http://localhost"); console.log(u.searchParams.get("limit"));
Expected output
3

Why this result follows: A one-value contract must still inspect duplicates rather than silently accepting first-wins.

17. Percent-decoded digit

Problem: Read a percent-encoded digit from a query parameter.

  1. The encoded byte sequence represents the character three.
  2. The decoded query value is text 3 and still requires domain validation.
javascript Percent-decoded digit
const u = new URL("/items?limit=%33", "http://localhost"); console.log(u.searchParams.get("limit"));
Expected output
3

Why this result follows: The decoded query value is text 3 and still requires domain validation.

18. Plus becomes space

Problem: Observe plus decoding in a query value under URLSearchParams.

  1. The plus sign is decoded as a space in query form encoding.
  2. The decoded value does not meet a digits-only limit grammar.
javascript Plus becomes space
const u = new URL("/items?limit=3+4", "http://localhost"); console.log(JSON.stringify(u.searchParams.get("limit")));
Expected output
"3 4"

Why this result follows: The decoded value does not meet a digits-only limit grammar.

19. Invalid skips query

Problem: Avoid a synthetic data-query call for a zero limit.

  1. Zero fails the inclusive lower-bound condition.
  2. The guarded query branch is skipped and its call count remains zero.
javascript Invalid skips query
let calls = 0; const n = 0; if (Number.isSafeInteger(n) && n >= 1 && n <= 100) calls++; console.log(calls);
Expected output
0

Why this result follows: The guarded query branch is skipped and its call count remains zero.

20. Valid query call

Problem: Allow one synthetic query call for validated limit three.

  1. Three satisfies the positive safe integer range.
  2. The validated branch records one query call under this synthetic policy.
javascript Valid query call
let calls = 0; const n = 3; if (Number.isSafeInteger(n) && n >= 1 && n <= 100) calls++; console.log(calls);
Expected output
1

Why this result follows: The validated branch records one query call under this synthetic policy.

Common errors and fixes

An empty parameter becomes zero

Why it happens
Numeric conversion was used without checking the original text.
How to fix it
Check the required digit format before conversion.
Prevent it next time
Test missing and empty parameters separately.

A repeated parameter is silently accepted

Why it happens
get returns only the first value while the application has no duplicate policy.
How to fix it
Use getAll and reject duplicates if the contract requires a single value.
Prevent it next time
Include duplicate query parameters in route tests.

Validation is mistaken for authorization

Why it happens
A valid limit says nothing about whether the caller may view the records.
How to fix it
Authorize the principal and use safe database query parameters.
Prevent it next time
Test unauthorized access separately from input validation.

20 practice exercises

1. What does parseLimit("3") return and why?

Show hint

The query value remains text until explicit conversion.

Show worked solution

It returns numeric 3: the text contains digits, the value is a safe integer, and it is within 1–100. The original query parameter remains text until this explicit conversion.

parseLimit("3") returns numeric 3 because the complete text contains digits, converts to a safe integer, and lies in the inclusive 1–100 range. The original query parameter is still text before that conversion.

Check your solution

  • The parsed value is numeric 3.
  • The digit, safety, and range checks pass.

2. How should a handler treat limit=0 and a missing limit?

Show hint

A present out-of-range zero differs from a missing key.

Show worked solution

Both are rejected under this example’s contract, for different reasons: zero is out of range and the other value is absent. The handler should return its documented client error and avoid executing the data query.

Reject both limit=0 and a missing limit under this required contract: zero fails the range and the other is absent. Return the documented client error and do not execute the data query. Test the distinct failure categories if the API exposes them.

Check your solution

  • Zero is rejected as out of range.
  • Missing limit is rejected and no query runs.

3. Parse GET /items?limit=3 and state the pathname and numeric limit.

Show hint

Route on pathname, then convert the validated parameter text.

Show worked solution

The pathname is /items and the raw limit is "3". Under the required digit and 1–100 policy, it converts to numeric 3. Match GET separately and test that only the validated number reaches the synthetic query.

Check your solution

  • The route pathname is /items
  • The numeric limit is 3

4. Compare limit=101 with limit= under the required digits-only range of 1 through 100.

Show hint

One decoded value exceeds the upper bound; the other is present but empty.

Show worked solution

Reject both before querying: "101" is a safe integer outside the upper range, while the empty value fails the required digit format. Return the documented client error and preserve distinct safe range and format categories if the contract exposes them.

Check your solution

  • limit=101 fails the upper-bound rule.
  • limit= fails the nonempty digit-format rule; neither request runs the query.

5. Validate limit=1 and limit=100 as inclusive boundary cases.

Show hint

Both values meet the digit, safety, and range checks.

Show worked solution

Both convert to safe integers at the inclusive endpoints and should be accepted. Assert numeric 1 and 100, then test 0 and 101 as immediate outside neighbors. Keep the original query text separate from the validated numeric value.

Check your solution

  • Limits 1 and 100 are accepted
  • Limits 0 and 101 are rejected

6. Reject limit=3x even though parseInt can return 3.

Show hint

Validate the complete decoded representation.

Show worked solution

The suffix x violates the digits-only grammar, so return a format error before the data query. parseInt reads a prefix and does not prove the entire value is valid. Test limit=3 as a separate accepted control.

Check your solution

  • The malformed value is rejected
  • The valid 3 control reaches the query

7. Reject duplicate limit=3&limit=4 under a single-value policy. Explain the documented handler outcome.

Show hint

Use getAll to count the parameter occurrences.

Show worked solution

getAll("limit") returns ["3", "4"], so reject the duplicate before converting either as the chosen limit. Using get alone would silently select the first value. Test exactly one occurrence and a missing key as separate cases.

Check your solution

  • The two values are detected
  • No data query runs for duplicates

8. Explain the difference between limit missing and limit= in URLSearchParams.

Show hint

A present empty value is not the same as no key.

Show worked solution

For a missing key, get("limit") returns null; for limit= it returns the empty string. Both are rejected by the stated required digit contract, but the handler can retain distinct absence and format categories. Test both targets explicitly.

Check your solution

  • Missing returns null
  • Present empty returns an empty string

9. Decide whether limit=003 is accepted when leading zeroes are explicitly allowed.

Show hint

The digit grammar and numeric range both apply.

Show worked solution

The decoded text "003" contains only digits and converts to numeric 3, so accept it under this stated policy. If the product forbids leading zeroes, add a separate grammar rule and test it; Number conversion cannot preserve the original representation.

Check your solution

  • The accepted numeric value is 3
  • The leading-zero policy is explicit

10. Reject limit=2.5 under the digits-only whole-number policy. Explain the format failure before querying.

Show hint

The decimal point violates the representation rule.

Show worked solution

Reject "2.5" as a format failure before conversion because the grammar permits only digits. Even if a different grammar converted it to a number, it would fail the integer domain rule. Assert that no data query runs.

Check your solution

  • The fractional text is rejected
  • The query call count remains zero

11. Validate the decoded value of limit=%33 under the stated policy.

Show hint

URLSearchParams decodes the encoded digit.

Show worked solution

searchParams.get returns the text "3", which passes the digit and 1–100 safe integer checks after conversion. The accepted numeric limit is 3. Validate the decoded value that will be used and document any additional raw-encoding restrictions separately.

Check your solution

  • The decoded text is 3
  • The numeric limit is 3

12. Explain why limit=3+4 does not meet a digits-only policy after query decoding.

Show hint

URLSearchParams decodes plus as a space in query form encoding.

Show worked solution

The decoded value is "3 4", which contains a space and fails the digits-only grammar. Reject it before conversion or querying. If whitespace normalization is desired, define it explicitly and test its consequences rather than assuming plus means numeric addition.

Check your solution

  • The decoded value contains a space
  • The digit-only policy rejects it

13. Reject a digit-only limit beyond safe integer precision.

Show hint

Syntax validity does not guarantee safe numeric representation.

Show worked solution

The text "9007199254740992" matches digits but Number.isSafeInteger of its converted value is false. Reject it before applying the 1–100 rule or querying. Test a small valid limit as a control and report the documented failure category.

Check your solution

  • The unsafe value is rejected
  • The data query is not called

14. Explain why URL parsing does not authorize access to the requested data.

Show hint

Routing and authorization are separate decisions.

Show worked solution

A parsed and valid limit only establishes request structure and value constraints. The trusted server must authenticate and authorize the actor for the requested resource before returning protected data. Test a valid query from a denied synthetic actor independently of parser tests.

Check your solution

  • The limit is validated
  • Authorization is checked separately

15. Test that invalid limit=0 does not invoke a synthetic data query.

Show hint

Use a recording fake after the validation boundary.

Show worked solution

Pass limit=0 to the handler and assert the documented client error and zero calls to the query fake. Pass limit=3 as a valid control and assert one call with numeric 3. This tests effects as well as parsing.

Check your solution

  • Invalid zero causes no query
  • Valid 3 produces one numeric query call

16. Explain why a required limit should not silently default when it is missing.

Show hint

Required and optional parameters have different contracts.

Show worked solution

Under the stated required policy, a missing key is a client error and no query should run. A default would change the contract and could hide a malformed request. If the product wants an optional default, document it and test missing, empty, and zero independently.

Check your solution

  • Missing limit is rejected
  • No default query runs under the required policy

17. Design a pure parser result distinguishing a valid limit from format and range failures.

Show hint

Use explicit tags or another documented nonambiguous result.

Show worked solution

Return a success containing numeric 3 for "3", a format failure for "3x", and a range failure for "0" under the stated order. Let the HTTP adapter map those outcomes to safe responses. Assert categories and ensure failure never calls the query.

Check your solution

  • Success carries numeric 3
  • Format and range failures remain distinguishable

18. Build a boundary table for a single required limit in 1–100.

Show hint

Cover missing, empty, endpoints, neighbors, format, and duplicates.

Show worked solution

Test missing and empty values, 1 and 100, 0 and 101, "3x", "2.5", an unsafe digit string, and two limit occurrences. Assert the documented category or numeric value and zero query calls for each invalid case.

Check your solution

  • Both inclusive endpoints pass
  • All stated invalid categories avoid the query

19. Explain why a passing local URL parser test does not prove the deployed handler is safe.

Show hint

The local parser is only one boundary.

Show worked solution

A passing test supports the specified parsing policy for its synthetic target. It does not prove actual HTTP routing, authorization, resource limits, or deployment configuration. Test the composed handler and trusted boundaries separately in an authorized environment.

Check your solution

  • The parser fixture behavior is verified
  • Deployment and authorization need separate evidence

20. Compare GET /items?limit=3 and POST /items?limit=3 for a GET-only route.

Show hint

A valid query does not make an unsupported method valid.

Show worked solution

Both targets parse to pathname /items and limit text "3", but only GET matches the stated route. POST must follow the documented unsupported-method path without executing the GET query. Test method and parameter validation as distinct decisions.

Check your solution

  • GET can reach validated query handling
  • POST does not enter the GET branch

Key takeaways

  • Parse URL structure before validating query values.
  • Define missing, duplicate, and range policies explicitly.
  • Query values are text until deliberately converted.
  • A required limit must satisfy syntax, safety, range, and occurrence policy.
  • Invalid parameters must not trigger the data query.

Official references