URLs · 11 min read

How to Recognize and Fix Double URL Encoding

The string %2520 sitting where a space should be is the tell-tale sign of a value that was percent-encoded twice — once by you, and once by a layer that did not know the first one existed.

Abstract illustration of a shape passing through two gates

Some bugs announce themselves with a stack trace. Double URL encoding announces itself with %2520 sitting in your logs where a space should be, a filename containing the literal text %2F, or a redirect that lands one layer of encoded gibberish away from the page you asked for. The pattern is common enough to have a signature: whenever a percent sign appears where a real character was supposed to arrive, some layer in the pipeline encoded a value that had already been encoded.

This guide walks through the mechanics — why percent-encoding is not idempotent and what each extra pass does to the data — then maps the places a second encoder tends to hide, shows how to recover a doubly encoded value without corrupting it, and lays out the discipline that prevents the problem: encode exactly once, at the boundary, and let every other layer keep its hands off the string.

What double encoding actually is

Percent-encoding replaces unsafe characters with a percent sign followed by two hexadecimal digits. A space becomes %20, an equals sign becomes %3D, a slash becomes %2F. The scheme works because the percent sign itself is reserved: in well-formed URL text, a raw % never appears except as the start of an escape, so a decoder can find the boundaries of every sequence unambiguously.

That guarantee is also what makes encoding non-idempotent. Feed an already-encoded string through the encoder again and the encoder does precisely what it is designed to do: it treats the percent signs in its input as unsafe characters and escapes them. %25 is the encoding of %. So a space encoded once is %20; encoded twice, the % of %20 becomes %25 and the string reads %2520. A third pass produces %252520. Nothing corrupts, nothing throws — the string simply grows one escape per encoded character per pass, and every layer in the chain sees text that looks like perfectly valid URL content.

const value = "blue shoes";
const once  = encodeURIComponent(value);   // "blue%20shoes"
const twice = encodeURIComponent(once);    // "blue%2520shoes"
const thrice = encodeURIComponent(twice);  // "blue%252520shoes"

The reason this happens so often is that every layer has a plausible excuse. Each encoder assumes it is the first to touch the value. A framework encodes parameters "for safety" by default. A redirect helper encodes the URLs it forwards. A template escapes by policy. A proxy rewrites paths defensively. Each layer, considered alone, is doing something defensible. Stacked, they multiply — and the output is wrong in a way that still looks syntactically clean, which is exactly why it survives code review, integration tests built on simple fixtures, and a demo that used an ASCII-only search term.

The tell-tale patterns

Once you know the signature, diagnosis is mostly visual. Scan the offending value for %25 followed by two hex digits. Each of those is a percent sign that itself got encoded, which means at least two passes happened. The most frequent combinations follow a pattern you can read at a glance:

PatternMeaningFix
%2520decodes once to %20 — a space that was encoded twiceremove one encoding layer upstream
%253Ddecodes once to %3D — an equals sign encoded twice, usually a key=value smuggled inside a parameterencode the inner URL once, not twice
%252Fdecodes once to %2F — a slash encoded twice, typical of redirect targetslet the redirect helper own the encoding
%2526decodes once to %26 — an ampersand encoded twicecheck for manual plus framework encoding
%253Fdecodes once to %3F — a question mark encoded twicesame: one layer must own it
%2525decodes once to %25 — a literal percent sign encoded twiceverify whether a literal percent was intended as data
%20, %3D, %2F as receivednormal single encoding; decodes to the real characterno action needed

One caution before you treat every %25 as a crime scene: %25 is also the only correct way to transmit a literal percent sign. The distinction is what follows. %2520 almost certainly conceals a space, because a user typing the six characters percent-two-zero is rare. A sequence like %257E decodes to a tilde — legal raw in a URL — so its presence usually points to a blanket encoder that escaped characters it never needed to touch. And watch for mixed depth: it is common for only part of a value to be doubly encoded, specifically the parameter the framework auto-encoded, joined with a substring the developer encoded by hand. Partial corruption is harder to spot than uniform corruption, and it survives tests built entirely on ASCII fixtures.

Where the second encoder hides

Double encoding is rarely the work of one bad line. It is the work of two correct-looking lines in different files, written by different people, at different times. These are the usual suspects.

Framework auto-encoding on top of manual encoding

The most common pairing: a developer calls encodeURIComponent on a value, then hands the result to a framework helper — a router builder, a URL generator, a form serializer — that encodes its inputs again by design. The framework's contract is usually "give me raw values, I produce the URL". Manual encoding upstream violates that contract, and the framework has no way to know the value arrived pre-encoded. The result is exactly one extra layer, every time, on every request.

Redirect chains

URLs traveling inside URLs is the canonical double-encoding scenario. A login flow carries the destination in a next parameter; a billing flow carries a return URL; an SSO handoff carries a callback. Each hop that re-wraps the URL adds a layer, and each hop that unwraps it removes one — the bug appears whenever the layers are asymmetric, which is easy to arrange when the hops live in different services. The anatomy of these flows, and the security reasons each hop must decode exactly once, are covered in redirect URLs in query parameters.

// The client encodes the return path before building the link:
const next = encodeURIComponent("/settings/profile?tab=notifications");
// "%2Fsettings%2Fprofile%3Ftab%3Dnotifications"

// The redirect handler builds a Location header from that value — and encodes again:
res.redirect("/login?next=" + encodeURIComponent(next));
// "/login?next=%252Fsettings%252Fprofile%253Ftab%253Dnotifications"

When the login page finally reads next and decodes it once, it holds %2Fsettings%2Fprofile%3Ftab%3Dnotifications — still encoded — and sends the user there if it is careless about validation. If it is careful, it rejects the value as malformed and the flow breaks silently.

Template layers

Template engines escape by policy, and some offer URL-escaping filters that get applied to interpolated values. When the value fed into the template was already encoded — because the controller encoded it, or because it came from a query string parse that also decoded it inconsistently — the filter adds a layer. Autoescaping features added in a security patch are a frequent trigger: code that worked before the patch starts shipping doubly encoded values the day the framework turns policy on, and nobody connects the regression to the upgrade.

Proxies and rewrite rules

An intermediary that rewrites paths "for safety" can encode segments that were already legal. Legacy gateways are repeat offenders: some re-encode incoming path segments before forwarding, others decode and re-encode, and a pipeline that passes through two such devices can gain a layer without a single line of your own code changing. When a value is doubly encoded in production but correct in every local environment, trace the infrastructure path first — the encoder may be a box you do not deploy.

Logging and display middleware

The sneakiest variant is the layer that never touches the request at all. A logging middleware that percent-encodes URLs before writing them — to keep log lines single-line-safe, or to make them terminal-friendly — will show you %2520 for values that traveled through the pipeline perfectly fine. The tell is that production logs look wrong but users see no symptoms: the page loads, the search works, the redirect lands. The fix is not in the request path but in the logger — log the raw value, or encode once if the sink genuinely requires it.

Before you change any code, ask whether anyone actually observed the bug. Doubly encoded text in a log viewer is often the logger's work, not the pipeline's. Fixing the wrong layer adds a third encoder to the codebase and makes the real problem harder to find next time.

Why decoding once is not enough

Handed a value like blue%2520shoes, the natural reflex is one call to decodeURIComponent. That produces blue%20shoes — better, but still not the data. The space is still hiding behind an escape, and if the value flows into a search index or a file path, the literal text %20 shows up in results. So the next reflex is to decode again, and eventually someone writes a helper that "keeps decoding until it works". Without guardrails that helper becomes its own bug: it strips legitimate escapes from values that were encoded exactly once, and it throws on inputs that were never encoded at all. The right approach is to make the decoding loop explicit and bounded, which is what the next section does.

How many times to decode: until stable, with guards

The rule is simple to state: decode repeatedly until the output stops changing, and stop early on anything suspicious. Three guards make it safe in practice. First, a hard cap on passes — a value that is still changing after five decodes is either deeply pathological or genuinely layered, and either way deserves human eyes, not an infinite loop. Second, a stability check: when a decode pass returns the input unchanged, the value has settled. Third, error handling: decodeURIComponent throws a URIError on a malformed sequence such as a bare % not followed by two hex digits, and that failure is informative — a value that decodes into something malformed was probably never meant to be decoded further.

function decodeUntilStable(s, maxPasses = 5) {
  let current = s;
  for (let i = 0; i < maxPasses; i++) {
    let next;
    try {
      next = decodeURIComponent(current);
    } catch (err) {
      return current;   // malformed sequence: settled, or never encoded
    }
    if (next === current) return current;  // no change: stable
    current = next;
  }
  return current;  // still changing after maxPasses: inspect manually
}

decodeUntilStable("blue%2520shoes");  // "blue shoes"        (two passes)
decodeUntilStable("blue%20shoes");    // "blue shoes"        (one pass)
decodeUntilStable("blue shoes");      // "blue shoes"        (zero passes)

A quick detection helper covers the diagnostic case, when you only want to flag suspicious values rather than transform them. A %25 immediately followed by two hex digits is almost never legitimate data:

function looksDoubleEncoded(s) {
  return /%25[0-9A-Fa-f]{2}/.test(s);
}

looksDoubleEncoded("blue%2520shoes");  // true
looksDoubleEncoded("blue%20shoes");    // false
looksDoubleEncoded("100%25");          // false — a literal percent, sent correctly

One honest limitation: decode-until-stable is a diagnostic and recovery tool, not a universal consumer policy. A value that legitimately contains the six-character text %2520 as user-typed data cannot be distinguished from a doubly encoded space — the bytes are identical. If your product lets users type percent sequences into search boxes, you must know the encoding history of each value rather than guessing at it, which is one more reason the durable fix lives at the encoding side, not the decoding side.

Fix the source, not the symptom

When you have located the layer that added the second pass, fix it there. The consumer-side decode loop from the previous section is scaffolding for diagnosis and for third-party senders you cannot change — it is not a permanent patch for a pipeline you control. Every blind decode you leave in a consumer is a latent corruption of some future value that arrives correctly encoded once.

The structural fix is to give each value a single owner and to build URLs from raw values with an API that does the encoding exactly once. URLSearchParams is the browser-native tool for the query portion: it takes values as opaque data, encodes them, and hands back a string you never touch again.

const params = new URLSearchParams({
  next: "/settings/profile?tab=notifications"
});
const url = "/login?" + params.toString();
// "/login?next=%2Fsettings%2Fprofile%3Ftab%3Dnotifications"

// On the receiving side, reading decodes exactly once, automatically:
new URLSearchParams("next=%2Fsettings%2Fprofile%3Ftab%3Dnotifications").get("next");
// "/settings/profile?tab=notifications"

With this pattern, the redirect handler no longer needs to know or care whether the client encoded anything — it receives raw values and re-encodes them deterministically. If you inherit a pipeline that must keep accepting doubly encoded values from a sender you cannot fix, quarantine the workaround: isolate the defensive decode to one function, name it for what it is, log every time it fires, and attach an issue link. A silent decode layer that sometimes runs will eventually corrupt a legitimate value, and the log is the only thing that will make that day survivable.

When double encoding is actually correct

There is one case where two layers of percent signs is exactly right: when the payload of a parameter is itself, by contract, already-encoded text. If an API documents that its url parameter expects a percent-encoded URL, then the percent signs in your payload are data, and data percent signs must be sent as %25. The same holds when a parameter forwards a value to a third service that will decode it again downstream.

The subtler cousin of this case is data that merely looks encoded. A user searching for the literal string %2B — perhaps studying this very guide — must have those four characters preserved exactly:

const query = "%2B";                 // the user typed a percent, a two, a B
encodeURIComponent(query);            // "%252B"  — looks like double encoding, is not
decodeURIComponent("%252B");          // "%2B"    — the original, correct data

The output %252B will trip every pattern-matching instinct you built reading the table above, and that is the point: the patterns identify suspicion, not guilt. The difference between contractual double encoding and accidental double encoding is intent and documentation. If a value in your system is deliberately encoded twice, leave a comment saying so — the next reader who sees %252B in a code review will otherwise "fix" it, and the corruption will run in the opposite direction this time.

Prevention: encode exactly once, at the boundary

Everything above compresses into a discipline small enough to fit on a card. Percent-encoding is safe when it is boring: one decision, one call site, one owner per value.

Locate the boundary for each value — the moment a raw string leaves the data world and enters the URL world — and encode there and only there. Which function belongs at that boundary is its own question; the difference between the two JavaScript encoders and the boundary each one protects is covered in encodeURI vs encodeURIComponent. Prefer builders that take raw values — URLSearchParams for queries, your framework's URL generator if its contract says raw input — because an API that accepts raw values makes double encoding impossible by construction. Never encode a string that already contains % sequences unless the contract explicitly demands it, and treat any code that encodes the same value twice, in two different layers, as a bug regardless of whether a test currently passes.

Finally, know how each hop in your pipeline decodes. Conventions differ — the plus sign meaning a space in form-encoded contexts versus a literal plus in generic URI syntax is the classic example, and plus signs and spaces untangles it — and a pipeline whose layers disagree about decoding will produce encoding bugs no matter how carefully any single layer behaves.

A checklist

  • Search logs and stored URLs for %25 followed by two hex digits; treat each hit as evidence of an extra encoding pass somewhere upstream.
  • Confirm the bug is real: reproduce with a value containing a space, a slash, and an ampersand, and check the actual bytes that arrive — not what the log viewer shows.
  • List every encodeURIComponent (or equivalent) call in the codebase and name the boundary each one protects; any value covered twice is the bug.
  • Check framework, template, and proxy documentation for automatic encoding, and for changes to autoescaping defaults since the last upgrade.
  • Decode for diagnosis with the guarded loop — capped passes, stability check, error handling — never as a blind first step in a consumer.
  • Fix at the source: one owner per value, one encode per value, raw values into builder APIs.
  • When double encoding is contractual, document it in place, with a comment the next reader cannot miss.

Test it yourself: paste a doubly encoded value like hello%2520world into the URL Workbench and decode repeatedly, watching the value settle one layer per pass until it stops changing. Then paste hello%20world and confirm it settles after a single decode — the contrast makes the layering visible in a way no table can. When a parameter carries a JSON payload inside a URL, the JSON Inspector will show you whether the embedded document survives the round trip intact or arrives with its quotes and colons still wearing escapes.

Reproduce every example locally with the JSON Inspector or the matching tool on the workbench. Nothing you paste leaves your browser.