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.
- 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 valueab+c/d==intoab c/d==. new URLSearchParams({ u: undefined, z: null })produced the literal stringsundefinedandnull.
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¬e=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¬e=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=2and?b=2&a=1are 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
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.