encodeURI or encodeURIComponent: Picking the Right Boundary

The two encoding functions answer different questions. Learn where each one draws the line and how to build URLs that survive parsing on every consumer.

On this page
AI-generated illustration; not taken on location · Illustration of a whole URL on one side and a single query value on the other, with two arrows labeled encodeURI and encodeURIComponent pointing at the correct scope of each.
AI-generated illustration; not taken on location · The two encoding functions answer different questions: one preserves the structure of a complete URL, the other escapes a single value as pure data.AI-generated illustration

One Value, Two Different Jobs

Almost every URL bug traced back to encoding has the same shape: the developer picked a function by name similarity instead of by scope. encodeURI and encodeURIComponent look interchangeable, and in most demos they even produce similar output.

The difference is one decision: is the text you are holding a complete URL whose structure must survive, or one piece of data that must be flattened into that structure? Answer the question first, and the choice of function stops being a coin flip.

Answer it wrong, and the failure modes are predictable. Pick the value-layer function for a whole URL and the delimiters get escaped, producing a link with literal %3F where the query should start. Pick the structure-preserving function for a value and delimiters pass through raw, splitting one parameter into two the moment a server parses it. Both directions lose information; only the direction you did not test shows it in production.

const value = 'q=summer&tag=sale';

encodeURI(value);           // 'q=summer&tag=sale'        — & survived, structure broken
encodeURIComponent(value);  // 'q%3Dsummer%26tag%3Dsale'   — everything escaped, safe

Everything that follows is about making that scope decision deliberate, once, at the layer that actually owns the value.

Encoding After the Fact Cannot Recover Intent

Consider a value that arrived already percent-encoded, say coffee%20mugs. Feeding it through either encoder produces coffee%2520mugs, because the percent sign itself now gets escaped.

The %20 that once meant a space has become literal text saying “percent two zero”. Decoding then re-decoding never restores the original, because the information about which percent sequences were intentional is gone the moment the second encoding ran.

const arrived = 'coffee%20mugs';
encodeURIComponent(arrived); // 'coffee%2520mugs'

decodeURIComponent('coffee%2520mugs'); // 'coffee%20mugs' — still encoded
decodeURIComponent('coffee%20mugs');   // 'coffee mugs'   — needs a second pass

Encoding is a one-way door at the moment of construction, and the only safe time to walk through it is once, at the exact layer that owns the value. Compensation passes — decode on one side because the other side encoded twice — produce pipelines that work for the demo data and fail on the first value containing an ambiguous character.

Where Each Function Draws the Line

The two functions differ in exactly one thing: their keep-list of characters. Everything else is escaped identically as UTF-8 percent sequences.

Function Leaves unescaped Designed for
encodeURI A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) # A full URL that must keep its scheme, path separators and query syntax
encodeURIComponent A-Z a-z 0-9 - _ . ! ~ * ' ( ) One value inside a URL: every delimiter becomes data

Read the keep-lists as intent. encodeURI protects syntax characters because its input is expected to be syntax-plus-data. encodeURIComponent trusts nothing structural because its input is expected to be pure data, including any characters that merely look like delimiters.

encodeURI('a/b').length === encodeURI('a/b').length; // 3 — '/' untouched
encodeURIComponent('a/b'); // 'a%2Fb' — '/' escaped

One quick diagnostic trick when reviewing unfamiliar code: encode a test value containing every delimiter with both functions and diff the outputs. The characters that differ are exactly the characters the code is making a decision about, knowingly or not.

Reserved Characters That Stay Visible

The characters a function does not escape define its blind spots. With encodeURI, every delimiter in the keep-list passes through untouched:

encodeURI('https://shop.example/search?q=summer&tag=sale');
// identical output — structure preserved, which is the point

That is correct behavior for a whole URL and a data-loss bug for a value. A query value genuinely containing & pushed through encodeURI splits into a second parameter the moment any server parses it.

// what the server sees after the split:
// q = 'summer'
// tag = 'sale'   — the intended single value 'summer&tag=sale' is gone

The delimiter was data, the function treated it as syntax, and the boundary broke in the direction that loses information. The same applies, with quieter symptoms, to = inside a value: it parses as a second separator in some lenient consumers and as garbage in strict ones, so the failure mode varies by client instead of being uniform and testable.

Building a URL From Pieces, Correctly

The pattern that survives review composes each layer with the function scoped to that layer:

const base = 'https://shop.example/search';
const params = new URLSearchParams({ q: 'coffee mugs & beans', tag: 'new' });
const url = base + '?' + params.toString();
// 'https://shop.example/search?q=coffee+mugs+%26+beans&tag=new'

URLSearchParams handles the value layer, including the &. The base string, which is pure structure, never passes through any encoder at all.

If a codebase avoids URLSearchParams, the manual equivalent is per-value encodeURIComponent joined by literal = and & characters that never themselves get encoded:

const pair = (k, v) => encodeURIComponent(k) + '=' + encodeURIComponent(v);
const query = pair('q', 'coffee mugs & beans') + '&' + pair('tag', 'new');

Both versions share one property worth calling out: encoding happens at the innermost layer, exactly once per value, and no layer above it touches the string again. That property, not the specific API, is what the checklist in the final section is really asking for.

One Construction Path, One Owner

Most double-encoding incidents are process bugs, not knowledge bugs. Three modules each “helpfully” encode the same value on its way to the request, and by the time the request leaves the app the space has become %2520.

// module A builds the value
const q = 'summer sale';
// module B "makes it safe"
const q1 = encodeURIComponent(q);        // 'summer%20sale'
// module C "also makes it safe"
const q2 = encodeURIComponent(q1);       // 'summer%2520sale' — shipped

The fix is organizational as much as technical. Pick one layer — usually the HTTP client wrapper — as the single place where URL construction and encoding happen. Everything upstream hands over raw, unencoded strings and says so in its types or documentation. Everything downstream of that layer treats its input as already-encoded and never re-encodes.

When a codebase has one construction path, “where did the encoding happen” has one answer, and diffing a failing request against a working one points straight at the violating module instead of at a list of three suspects.

Spaces, Plus Signs and Repeated Names

Three query-specific traps sit just past the function choice, and they explain a large share of “works in the browser, fails in the service” reports.

Space representation. Percent encoding says %20; the application/x-www-form-urlencoded convention says +. URLSearchParams.toString() emits +, which is correct for form bodies but must be decoded as a space only in that context.

new URLSearchParams({q: 'summer sale'}).toString(); // 'q=summer+sale'
encodeURI('summer sale');                           // 'summer%20sale'

The plus as data. A value that legitimately contains +, like a phone number or a version constraint, needs %2B in query context or it will read back as a space:

const phone = '+1 555 0100';
new URLSearchParams({p: phone}).toString(); // 'p=%2B1+555+0100' — plus escaped, space is '+'

Repeated parameters. ?tag=a&tag=b is the unambiguous way to carry two values under one name. Arrays joined with commas inside one parameter look tidier but force every consumer to split on a character that might belong to the data. Server frameworks disagree about whether repeated keys arrive as a list, a last-value-wins string, or a joined string, so the repeated-key form is the only one with predictable behavior across stacks.

When the Same Value Got Encoded Twice

Double encoding announces itself with a small signature: decoded output still contains percent sequences. %2520 decodes once to %20, which decodes again to a space.

const shipped = 'summer%2520sale';
decodeURIComponent(shipped); // 'summer%20sale' — one pass is not enough

If one decode pass leaves percent escapes in a value that should contain none, some layer encoded twice. Trace it by walking the construction path in reverse and asking at each hop: did this module know whether its input was raw or encoded? The bug lives at the hop where the assumption was wrong.

Resist the temptation to fix it by adding a decode to compensate. That produces a pipeline that only works for values with no ambiguous characters, and it fails later on a value that has one — usually a + or a % in user input, which is to say on the input you most needed to be correct. The durable fix is always to remove the extra encoding hop, not to add a decoding hop after it.

Lone Surrogates Need a Decision, Not a Crash

Both functions percent-encode UTF-8, and UTF-8 has no encoding for an unpaired surrogate code unit. Hand one to encodeURI in an engine that still tolerates it and the output is either an escape sequence that does not decode back, or a URIError, depending on the runtime.

const bad = 'text \uD800 tail'; // contains a lone surrogate
encodeURI(bad);
// URIError: URI malformed — in engines that validate
// or an undecodable escape sequence — in engines that do not

The robust posture is to decide before encoding. String.prototype.toWellFormed() replaces lone surrogates with the replacement character, making the encoding lossless in the “no exception, decodable output” sense:

encodeURIComponent(bad.toWellFormed()); // encodes U+FFFD where the surrogate was

The alternative — rejecting the input with a clear error — is equally valid and better for API boundaries, where silent replacement can hide an upstream bug. What is not valid is passing the decision to the encoder and letting the runtime pick, because different clients in your user base will pick differently and your data will diverge in ways no test catches.

A Checklist That Fits in a Code Review

Compressed to review checklist size, the whole topic is five questions, each with a one-line acceptance rule:

  1. Is this text a whole URL or one value? Whole URL: encodeURI or no encoding. One value: encodeURIComponent.
  2. Does the value contain characters that are delimiters in query context? They must be escaped, so the value-layer function is mandatory.
  3. Is there exactly one encoding hop on the construction path? More than one is a bug even when today’s test data survives it.
  4. Are repeated parameters carried as repeated keys rather than pre-joined strings?
  5. Can the value contain lone surrogates? Then a well-formedness decision belongs upstream of the encoder.

Two of these questions can be enforced mechanically. A lint rule that flags encodeURI calls on string concatenation into URLs, and a CI fixture that round-trips a payload full of delimiters, spaces and repeated keys, catch the two most common regressions before they merge.

Run a suspect URL through the workbench on this site to see each component and each query value split out and re-encoded the way the checklist prescribes. The processing is local to the browser, the input never leaves the machine, and the mismatch between what you wrote and what the parser sees is visible side by side.