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

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 →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

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 →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Software Development

Python Multiprocessing: Pool, Processes, Queues and Real Timings

Python multiprocessing timed: Pool vs a loop, start-up overhead, chunksize, the main guard, exceptions, shared values with locks, queues and…

Read article →
Software Development

Python __slots__ Explained: Memory Savings, Speed and 6 Traps, Tested

Python __slots__ explained and measured on Python 3.13: memory savings, attribute speed, dataclass slots=True, and six traps including inheritance, weakref…

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 →
Software Development

Content Security Policy Explained: Nonces, strict-dynamic and Report-Only

Content security policy explained: nonces, strict-dynamic, Report-Only, eval, image and style rules, tested in a real browser, plus a strict…

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 →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Software Development

JavaScript Proxy Explained: All 13 Traps, Reflect and Real Use Cases

JavaScript Proxy explained: all 13 traps, Reflect, validation, defaults, hidden keys, revocable proxies, private field problems and the speed cost,…

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 →
Databases & SQL

SQL Random Rows: How to Select Random Rows Fast and Fairly

SQL random rows: how to select random rows fast and fairly, timing ORDER BY RANDOM, offsets and ID jumps, and…

Read article →
Databases & SQL

SQL Median: 4 Ways to Calculate the Median, With Tested Queries

SQL median explained: four tested ways to calculate the median, including percentile functions, window ranks, offsets and per group medians.

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 →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →
Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →