URL Query Parameters: Encoding, Decoding, and Best Practices
Query parameters are one of the simplest ways to pass state through a URL. Search terms, filters, pagination, tracking parameters, and feature flags often live after the question mark. They are easy to use, but small encoding mistakes can change the meaning of a request.
Understand the parts of a URL
A URL can include a scheme, host, path, query string, and fragment. Query parameters appear after? and are usually separated with &. The fragment appears after# and is not normally sent to the server. Mixing these parts up can produce confusing bugs.
Encode parameter values, not the whole URL
A common mistake is encoding an entire URL when only one parameter value should be encoded. If the value contains spaces, ampersands, equals signs, or another URL, encode that value before appending it to the query string. Encoding the whole URL can turn separators into text and break routing.
Use URLSearchParams when possible
In modern JavaScript, URL and URLSearchParams handle most query string work safely. They encode values, preserve repeated keys, and make it easier to add or remove parameters without manual string concatenation.
Repeated keys are valid
Some APIs represent arrays with repeated keys, such as ?tag=json&tag=api. Others use comma-separated values or bracket notation. There is no single universal convention, so check the API contract before assuming how multiple values should be represented.
Keep sensitive data out of URLs
URLs are commonly stored in browser history, server logs, analytics tools, referrer headers, and shared screenshots. Do not put passwords, private tokens, or sensitive personal data in query parameters. Prefer request bodies or secure headers for sensitive information.
Normalize before comparing
Two URLs can be equivalent while their query strings appear in a different order. If you are comparing URLs in tests or caches, normalize parameter order and encoding first. Otherwise, harmless differences can cause cache misses or brittle assertions.
Decode carefully while debugging
Decoding a query string makes it easier to read, especially when values contain nested URLs or JSON. But do not repeatedly decode the same value without checking the source. Double-decoding can turn safe encoded text into active separators and change how an application interprets the request.
Try it now