1. Home
  2. Blog
  3. Software Development

Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters are the key=value pairs after the question mark in a link, used for searches, filters, pagination and tracking. Reading and building them looks easy until a value contains an ampersand, a plus sign or an accented letter. We tested URLSearchParams in Node.js and urllib in Python against nine traps that break real applications.

9 min read
URL query parameters: encoding, URLSearchParams and common traps

Key takeaways

  • URL query parameters are name=value pairs after ?, separated by &; values must be percent-encoded.
  • Gluing "Tom & Jerry" into a URL by hand produced two broken parameters; URLSearchParams encoded it correctly.
  • URLSearchParams decodes + as a space, which turned the Base64 value ab+c/d== into ab c/d==.
  • new URLSearchParams({ u: undefined, z: null }) produced the literal strings undefined and null.

Every search box, product filter and paginated list puts state into the URL: ?q=red+shoes&size=9&page=2. That makes pages shareable and bookmarkable, and lets servers and caches see what was requested. It also means user-typed text ends up inside a URL, where characters such as &, =, +, # and spaces have special meanings. Handling URL query parameters correctly is mostly about encoding.

We ran the JavaScript examples in Node.js v24.22.1 (URLSearchParams behaves the same in browsers) and the Python examples in Python 3.13.6.

Anatomy of a URL

https://shop.example.com/search?q=red+shoes&size=9&size=10#reviews

scheme        https
host          shop.example.com
path          /search
query string  q=red+shoes&size=9&size=10
fragment      reviews

The query string starts after ? and ends at # or the end of the URL. Pairs are separated by &, names and values by =. The fragment after # is never sent to the server. Spaces and other unsafe characters are percent-encoded as % plus two hex digits, and in form-style query strings a space may also be written as +.

Reading parameters with URLSearchParams

const u = new URL("https://shop.example.com/search?q=red+shoes&size=9&size=10&sort=price&empty=&flag");
const p = u.searchParams;
p.get("q")          // 'red shoes'
p.get("size")       // '9'          only the first value
p.getAll("size")    // [ '9', '10' ]
p.get("empty")      // ''
p.get("flag")       // ''           present without a value
p.get("missing")    // null
p.has("flag")       // true
[...p.keys()]       // [ 'q', 'size', 'size', 'sort', 'empty', 'flag' ]
p.size              // 6

URL parses the whole address and exposes a live searchParams object. get decodes the value for you, returns only the first value of a repeated key, and returns null when the key is missing, which is different from the empty string for a key with no value. All values are strings: "9", not 9. Convert and validate them before use.

Changing parameters

p.set("page", "2");     // add or replace
p.append("size", "11"); // add another value
p.delete("flag");
p.sort();
u.toString()
// https://shop.example.com/search?empty=&page=2&q=red+shoes&size=9&size=10&size=11&sort=price

Changes to searchParams update the URL object directly. sort() orders keys alphabetically while keeping repeated keys in their original order, which is useful for producing one canonical URL per filter combination, so caches and analytics do not count the same page twice. In a browser, history.replaceState can push the new URL to the address bar without reloading.

Building query strings safely

new URLSearchParams({ q: "café & bar", note: "50% off", plus: "a+b", path: "/x/y?z" }).toString()
// q=caf%C3%A9+%26+bar&note=50%25+off&plus=a%2Bb&path=%2Fx%2Fy%3Fz

Pass an object, an array of pairs or an existing string to the constructor, and toString() encodes every name and value. The accented é became UTF-8 bytes %C3%A9, & became %26, % became %25, a literal plus became %2B, and spaces became +. Then use it with fetch: fetch(`/api/items?${params}`). As our fetch API guide notes, fetch does not encode query values for you.

Trap 1: building URLs with string concatenation

const naive = "https://api.example.com/items?name=" + "Tom & Jerry";
Object.fromEntries(new URL(naive).searchParams)
// { name: 'Tom ', ' Jerry': '' }

The unencoded & split the value into two parameters: name became “Tom ” and a second, nonsense key ” Jerry” appeared. With user input this is not only a bug but a security problem, because a user can inject extra parameters such as &admin=true or &price=0. Never concatenate raw values into URLs.

Trap 2: plus signs

new URLSearchParams("token=abc+def").get("token")   // 'abc def'
decodeURIComponent("abc+def")                       // 'abc+def'

In query strings, URLSearchParams follows the HTML form rules, where + means a space. decodeURIComponent follows the general URI rules, where + is just a plus. The two decoders disagree on the same input. International phone numbers that start with a plus, email aliases like a+tag@example.com and maths expressions all break if a literal plus is not encoded as %2B on the way in.

Trap 3: Base64 and tokens

new URLSearchParams("t=ab+c/d==").get("t")                          // 'ab c/d=='
new URLSearchParams("t=" + encodeURIComponent("ab+c/d==")).get("t") // 'ab+c/d=='

Base64 strings contain +, / and =. Unencoded, the plus became a space and the token was corrupted, a classic cause of “invalid signature” errors in password-reset and OAuth links. Encode tokens, or use the URL-safe Base64 variant that replaces + and / with - and _.

Trap 4: double encoding

encodeURIComponent(encodeURIComponent("a b"))   // 'a%2520b'
decodeURIComponent("a%2520b")                    // 'a%20b'

Encoding a value that is already encoded turns % into %25, so the server decodes it once and receives a literal %20 instead of a space. It usually happens when one layer encodes and another layer encodes again, for example a helper plus URLSearchParams, or a value copied from an already-encoded URL. Encode exactly once, at the point where you build the URL.

Trap 5: encodeURI vs encodeURIComponent

encodeURIComponent("café & bar")                  // 'caf%C3%A9%20%26%20bar'
encodeURIComponent("a+b")                         // 'a%2Bb'
encodeURI("https://x.com/a b?q=a&b")              // 'https://x.com/a%20b?q=a&b'

encodeURIComponent encodes everything except letters, digits and -_.!~*'(), so it is right for a single value. encodeURI keeps ?, &, =, / and # intact because it assumes you are encoding a whole URL; it left the & in “a&b” unencoded. Use encodeURIComponent (or URLSearchParams) for values, and encodeURI only for complete, trusted URLs. Note the space: %20 here, + from URLSearchParams. Servers accept both in query strings.

Trap 6: repeated keys and arrays

const arr = new URLSearchParams();
["a", "b"].forEach(t => arr.append("tag", t));
arr.toString()                                   // 'tag=a&tag=b'
new URLSearchParams({ "tag[]": "a" }).toString() // 'tag%5B%5D=a'

There is no standard way to send an array in a query string. Repeating the key is the most widely supported convention; PHP and Rails expect tag[]=a; other APIs want tags=a,b. Check what your server framework expects, and remember that reading with get() silently drops all but the first value.

Trap 7: null, undefined and booleans

new URLSearchParams({ n: 1, t: true, u: undefined, z: null }).toString()
// 'n=1&t=true&u=undefined&z=null'

Every value is converted to a string, so an optional filter left as undefined was sent as the literal word “undefined”. The server then searched for it. Remove empty values before building the query: Object.entries(obj).filter(([, v]) => v != null).

Trap 8: empty values disappear in Python

from urllib.parse import parse_qs
parse_qs("size=9&size=10&empty=&flag")                  # {'size': ['9', '10']}
parse_qs("empty=&flag", keep_blank_values=True)         # {'empty': [''], 'flag': ['']}

Python’s parse_qs drops parameters with empty values unless you pass keep_blank_values=True, while URLSearchParams keeps them. If “present but empty” means something in your API (such as clearing a filter), make both sides agree.

Trap 9: parameters after the fragment

new URL("https://x.com/p?a=1#b=2").searchParams.get("b")   // null
new URL("https://x.com/p#x?a=1").searchParams.get("a")     // null

Everything after # is the fragment, not the query, even if it looks like parameters. Single-page apps sometimes store state there; read it from url.hash instead. And because fragments are not sent to the server, they never appear in server logs, which is why some apps use them for sensitive values.

Query parameters in Python

from urllib.parse import urlencode, parse_qsl, quote, quote_plus, urlparse
urlencode({"q": "café & bar", "note": "50% off"})   # q=caf%C3%A9+%26+bar&note=50%25+off
urlencode({"size": [9, 10]}, doseq=True)          # size=9&size=10
urlencode({"size": [9, 10]})                      # size=%5B9%2C+10%5D   (the list as text!)
parse_qsl("token=abc+def")                        # [('token', 'abc def')]
quote("a b+c"), quote_plus("a b+c")               # 'a%20b%2Bc' 'a+b%2Bc'
urlparse("https://shop.example.com/search?q=red+shoes#top").query   # 'q=red+shoes'

urlencode produced the same encoding as URLSearchParams. Without doseq=True, a list was turned into its text representation, [9, 10], instead of repeated keys. In practice, the requests library’s params= argument handles all of this for you, as shown in our API testing guide for the Postman equivalent.

Designing query parameters for an API

  • Use them for filtering, sorting, searching and pagination of GET requests. Put resource IDs in the path and data that changes state in the request body, following REST API best practices.
  • Never put secrets such as passwords or long-lived tokens in query strings: they end up in browser history, server logs, analytics and the Referer header.
  • Keep URLs reasonably short. Our parser accepted a 5,017-character URL, but servers, proxies and CDNs impose their own limits, commonly a few kilobytes; we did not test those.
  • Canonicalise parameter order for caching, since ?a=1&b=2 and ?b=2&a=1 are different cache keys, as explained in our HTTP caching guide.
  • Validate and limit every value on the server: types, ranges and allowed sort fields, and protect expensive searches with API rate limiting.
  • Remember CORS when a browser on another origin calls your API with query parameters; the rules are in our CORS guide.

Final thoughts

URL query parameters are simple key=value pairs wrapped in tricky encoding rules. Build them with URLSearchParams or urlencode, never by concatenation; encode each value exactly once; watch plus signs, Base64 tokens and repeated keys; drop null and undefined values; and remember that everything after # is not a parameter at all. Our nine tests show that each trap is easy to hit and just as easy to avoid with the right tool.

Frequently asked questions

What are URL query parameters?

Name and value pairs added to a URL after a question mark and separated by ampersands, used to pass filters, search terms, pagination and other options to a page or API.

How do I get a query parameter in JavaScript?

Create a URL object from the address and call searchParams.get with the name. It returns the decoded value, or null if the parameter is missing.

Should spaces be encoded as plus or percent 20?

Both work in query strings. URLSearchParams uses plus, encodeURIComponent uses percent 20. In paths, only percent 20 is correct, and a literal plus in a value must be sent as percent 2B.

How do I pass an array in a query string?

The most common way is to repeat the key, such as tag=a and tag=b, and read it with getAll. Some frameworks expect square brackets or comma-separated values instead.

Is it safe to put tokens in query parameters?

Avoid it for secrets. Query strings are stored in browser history and server logs and can leak through the Referer header. Use headers or the request body instead.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →