Percent-encoding bugs rarely announce themselves as encoding bugs. They appear as a search query that arrives with plus signs, a redirect that loops, an OAuth callback that fails only for an internationalized value, or an API that receives %2520 where it expected one space.
The usual cause is using one encoder for every part of a URL. JavaScript exposes several related functions, but they answer different questions:
URLSearchParams serializes form data.
encodeURIComponent encodes a URI component.
encodeURI encodes a complete URI while preserving separators.
new URL() parses and normalizes a URL.
Those APIs overlap, but they are not interchangeable.
A space can be %20 or +
Start with the smallest example:
encodeURIComponent("a b");
// "a%20b"
new URLSearchParams({ q: "a b" }).toString();
// "q=a+b"
Both outputs are valid in their intended context. %20 represents a space byte in URI syntax. + represents a space in application/x-www-form-urlencoded, the format used by HTML form submissions and by URLSearchParams.
The ambiguity appears when a value is decoded by the wrong parser:
new URLSearchParams("q=a+b").get("q");
// "a b"
new URLSearchParams("q=a%2Bb").get("q");
// "a+b"
decodeURIComponent("a+b");
// "a+b"
URLSearchParams treats an unescaped + as a space. decodeURIComponent does not. If a + is part of the original value, it must be encoded as %2B before the value is placed in form-style data.
This is why “just decode the query string” is not a complete rule. The parser must match the producer.
encodeURIComponent is for components
encodeURIComponent is the better default for one path segment or one query value:
const value = "https://example.com/a b?x=1";
encodeURIComponent(value);
// "https%3A%2F%2Fexample.com%2Fa%20b%3Fx%3D1"
That output is correct if the entire value is data inside another parameter. It is wrong if the goal was to encode only the path portion of a URL while keeping https:// and the query delimiter readable:
encodeURI("https://example.com/a b?x=1");
// "https://example.com/a%20b?x=1"
encodeURI preserves characters that have structural meaning in a complete URI, including :, /, ?, #, &, and =. That makes it useful for readable examples, but it is not a general-purpose query-value encoder.
The practical rule is:
Input
Suitable encoder
One query parameter value
URLSearchParams, or a strict component encoder
One path segment
encodeURIComponent plus a policy check for !'()*
A complete URL
new URL() for structure; do not encode the whole string
An HTML form submission
URLSearchParams / application/x-www-form-urlencoded
Binary data
Use bytes and the correct transport encoding, not URL encoding
Unicode is encoded as UTF-8 bytes
Percent-encoding operates on bytes. JavaScript strings contain UTF-16 code units, so the runtime must convert them to UTF-8 first.
encodeURIComponent("你好");
// "%E4%BD%A0%E5%A5%BD"
decodeURIComponent("%E4%BD%A0%E5%A5%BD");
// "你好"
Each Chinese character becomes three UTF-8 bytes:
你 -> E4 BD A0
好 -> E5 A5 BD
An emoji can require four UTF-8 bytes and therefore a longer percent sequence. The visible character count is not the encoded byte count.
This matters when building signatures, OAuth URLs, redirect URIs, webhook parameters, or request caches. Two strings that look equivalent in JavaScript can produce different bytes if one has undergone normalization. For identifiers and security-sensitive values, compare the exact encoded form required by the receiving system instead of relying on visual similarity.
Encode once, at the boundary
Double encoding happens when an already encoded value is passed through the same encoder again:
const once = encodeURIComponent("a b");
const twice = encodeURIComponent(once);
once; // "a%20b"
twice; // "a%2520b"
The second operation did not corrupt the string. It correctly encoded the % character in the first result. The bug is architectural: the value crossed an encoding boundary twice.
Keep a simple state model:
Keep application values decoded.
Encode when constructing the query string.
Decode once when parsing it.
Do not re-encode a value that is already in transport form unless the protocol explicitly says so.
Logging helps separate the states. Record the decoded value and the final URL, but never assume that a readable browser address bar means the server received the same representation.
Path and query encoding are different jobs
A URL is not one opaque value. It has components with different delimiters:
https://example.com/users/Alice Smith?q=a+b&sort=created#profile
The valid construction is component-aware:
const url = new URL("https://example.com/");
url.pathname = /users/${encodeURIComponent("Alice Smith")};
url.searchParams.set("q", "a+b");
url.searchParams.set("sort", "created");
url.hash = "profile";
console.log(url.href);
// https://example.com/users/Alice%20Smith?q=a%2Bb&sort=created#profile
Note that the original + inside the query value became %2B. Otherwise the next URLSearchParams parser would read it as a space.
new URL() validates structure
Use the URL parser before applying string substitutions:
try {
const u = new URL(input);
console.log({
protocol: u.protocol,
hostname: u.hostname,
pathname: u.pathname,
query: Object.fromEntries(u.searchParams),
});
} catch {
console.error("Invalid absolute URL");
}
This catches missing schemes, malformed IPv6 hosts, bad ports, and other structural failures that string concatenation obscures. It also exposes parsed query values through the form-style decoder, which is useful when that is the protocol in use.
For a relative URL, provide a base explicitly:
new URL("../guide?lang=en", "https://www.example.com/docs/start/");
Do not assume that a browser will preserve every input byte. Host normalization, default-port removal, path normalization, and query serialization can all change the final URL.
A verification pass that catches real failures
Before sending a constructed URL:
Round-trip ASCII, Unicode, emoji, spaces, +, %, &, =, ?, /, and #.
Assert whether spaces are expected as %20 or +.
Confirm whether the receiver expects one or several query values with the same key.
Decode once and compare the resulting value with the original application value.
Reject malformed % sequences instead of silently replacing them.
Inspect the final absolute URL after new URL() normalization.
Never log credentials, access tokens, API keys, or sensitive query parameters.
The JsonMind URL encoder and decoder can reproduce the %20, +, Unicode, and malformed-input cases in the browser. The URL parser is useful for checking host, path, query, and fragment boundaries separately.
Percent-encoding is not one operation. It is a family of transformations tied to a specific URL component and protocol. Once those boundaries are explicit, most “URL encoding is broken” reports become short, reproducible test cases.
The author maintains JsonMind. The examples were checked with Node.js 24.17.0 and the WHATWG URL implementation it provides.
Top comments (0)