• Web
  • Encoding
  • JavaScript

encodeURI vs encodeURIComponent: URL encoding bugs and how to avoid them

What each JavaScript encoder escapes, why + and %20 differ, how double encoding happens, and how to build URLs that don't break on real input.

The utilyx team7 min read
On this page

A user searches your shop for fish & chips and gets results for fish. The code that built the request looks harmless:

js
const q = "fish & chips";
const url = `https://shop.example/search?q=${q}`;

Ask the URL parser what it sees and the bug is obvious:

js
const u = new URL(`https://shop.example/search?q=${q}`);
u.searchParams.get("q");   // "fish "
[...u.searchParams.keys()]; // ["q", " chips"]

The & ended the parameter. Nobody wrote a parser bug here. The URL said exactly what it was told to say. Every URL encoding bug comes down to the same mistake: a character that means structure ended up where data belonged, or the reverse. Below: which characters are which, what each JavaScript function really escapes, and how to let the URL APIs carry the burden instead of you.

Reserved, unreserved, and everything else

RFC 3986 sorts ASCII into three groups:

  • Unreserved (§2.3): A–Z a–z 0–9 - . _ ~. Always safe, never need escaping. The RFC says producers should not percent-encode them.
  • Reserved (§2.2): the delimiters that give a URL its shape. : / ? # [ ] @ are gen-delims; ! $ & ' ( ) * + , ; = are sub-delims. They're legal, but only in their structural role. Used as data, they must be escaped.
  • Everything else: space, " % < > \ ^ ` { | }, control characters, and all non-ASCII text. These must always be encoded.

Percent-encoding writes a byte as % plus two hex digits. Text is first converted to UTF-8, so é (two bytes) becomes %C3%A9 and 日本 (six bytes) becomes %E6%97%A5%E6%9C%AC. §2.1 asks producers to use uppercase hex digits, which every function in this post does.

What each JavaScript function escapes

We ran every printable ASCII character (0x20–0x7E) through encodeURI, encodeURIComponent and URLSearchParams in Node 26 and grouped the results. "Kept" means the character came out unchanged.

CharactersencodeURIencodeURIComponentURLSearchParams
A–Z a–z 0–9 - . _ *KeptKeptKept
~KeptKept%7E
! ' ( )KeptKeptEscaped
# $ & + , / : ; = ? @KeptEscapedEscaped
Space%20%20+
" % < > [ \ ] ^ ` { | }EscapedEscapedEscaped
Non-ASCII, e.g. é%C3%A9%C3%A9%C3%A9

The table gives you the rule for each one:

  • encodeURI assumes you hand it a whole URL and leaves every delimiter alone. That's why it can't protect a value: &, =, # and ? pass straight through. It also escapes [ and ], which breaks IPv6 hosts: encodeURI("http://[::1]:8080/") returns http://%5B::1%5D:8080/.
  • encodeURIComponent assumes you hand it one piece: a query value, a path segment, a fragment. It escapes every delimiter except the sub-delims ! ' ( ) *.
  • URLSearchParams follows the WHATWG application/x-www-form-urlencoded rules, the format HTML forms submit, which is stricter still and turns spaces into +.

If you need strict RFC 3986 output, for example when computing an OAuth 1.0 or AWS SigV4 signature where the server re-encodes and compares, escape the five leftovers yourself:

js
const encodeRfc3986 = (s) =>
  encodeURIComponent(s).replace(/[!'()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());

encodeRfc3986("!'()*"); // "%21%27%28%29%2A"

Both encoders throw on a lone UTF-16 surrogate, such as a string sliced through the middle of an emoji. encodeURIComponent("\uD800") fails with URIError: URI malformed. The decoders throw the same error on a bare % (decodeURIComponent("100%")) or a truncated UTF-8 sequence like %C3. Wrap decoding of untrusted input in try.

+ versus %20

There are two encodings for a space, and they belong to different specs. RFC 3986 only knows %20. Form encoding, inherited from HTML, uses +, and only in the query string. In a path, + is just a plus sign.

Trouble starts when one side encodes with one convention and the other decodes with the other. decodeURIComponent knows nothing about forms:

js
decodeURIComponent("fish+%26+chips");               // "fish+&+chips"
new URLSearchParams("q=fish+%26+chips").get("q");   // "fish & chips"

The reverse bug is more common and nastier, because it eats real data. Build a query by hand without encoding, and every literal + becomes a space on the server:

js
new URLSearchParams("email=user+tag@example.com").get("email");
// "user tag@example.com"

Plus-addressed emails, phone numbers in +1 format and standard base64 strings all get damaged this way. The fix is to encode the value, which turns + into %2B.

One quieter trap: touching url.searchParams reserializes the entire query in form style.

js
const u = new URL("https://example.com/search?q=a%20b");
u.searchParams.set("page", "2");
u.href; // "https://example.com/search?q=a+b&page=2"

Both forms mean the same thing to a form decoder, but a pre-signed URL whose signature covers the exact query string will now fail verification. If a URL is signed, append to it as a string or re-sign it. Don't round-trip it through searchParams.

Double encoding, and double decoding

Encoding is not idempotent. Run it twice and the % signs from the first pass get encoded as %25:

js
encodeURIComponent("fish & chips");                     // "fish%20%26%20chips"
encodeURIComponent(encodeURIComponent("fish & chips")); // "fish%2520%2526%2520chips"

If you see %25 followed by two hex digits in a URL or a log, something encoded an already-encoded string. The usual cause is two layers that each think they own encoding: a helper that calls encodeURIComponent and then passes the result to an HTTP client or searchParams.set, which encode again.

js
const u = new URL("https://example.com/");
u.searchParams.set("q", encodeURIComponent("fish & chips"));
u.href;                  // "https://example.com/?q=fish%2520%2526%2520chips"
u.searchParams.get("q"); // "fish%20%26%20chips"   (the server sees this)

RFC 3986 §2.4 is blunt about it: implementations must not percent-encode or decode the same string more than once. Pick one layer to encode, at the moment you put data into a URL, and keep raw values everywhere else.

Decoding twice is the security version of the same bug. A filter checks a path for ../, decodes once, finds nothing, and passes it on to code that decodes again:

js
const p = "%252e%252e%252f";
decodeURIComponent(p);                     // "%2e%2e%2f"  (passes the check)
decodeURIComponent(decodeURIComponent(p)); // "../"

It's common enough to have its own entry, CWE-174: Double Decoding of the Same Data. Validate after the final decode, never before it.

Build URLs with URL and URLSearchParams

The reliable fix for all of the above is to stop concatenating strings. URL and URLSearchParams exist in every modern browser and in Node, and they know which characters need escaping in which part of the URL:

js
const u = new URL("https://api.example.com/search");
u.searchParams.set("q", "fish & chips");
u.searchParams.set("redirect", "https://app.example.com/cb?x=1&y=2");

u.href;
// "https://api.example.com/search?q=fish+%26+chips&redirect=https%3A%2F%2Fapp.example.com%2Fcb%3Fx%3D1%26y%3D2"

u.searchParams.get("redirect");
// "https://app.example.com/cb?x=1&y=2"

Repeated keys use append and come back with getAll. set replaces.

Paths still need encodeURIComponent

The pathname setter escapes spaces, ? and #, but it can't know whether a / is a separator or part of a file name. Encode each segment and join them yourself:

js
const segments = ["reports", "Q3 / 2026", "café.pdf"];
const u = new URL("https://example.com/");
u.pathname = "/" + segments.map(encodeURIComponent).join("/");

u.href; // "https://example.com/reports/Q3%20%2F%202026/caf%C3%A9.pdf"

This matters for more than tidiness. An unencoded ID that contains ../ gets resolved by the parser, and your request lands on a different endpoint:

js
const id = "../admin";
new URL(`https://api.example.com/users/${id}`).href;
// "https://api.example.com/admin"

new URL(`https://api.example.com/users/${encodeURIComponent(id)}`).href;
// "https://api.example.com/users/..%2Fadmin"

The trailing slash on a base URL

Resolving a relative path against a base URL replaces the base's last segment unless the base ends in /:

js
new URL("users/42", "https://api.example.com/v1").href;  // "https://api.example.com/users/42"
new URL("users/42", "https://api.example.com/v1/").href; // "https://api.example.com/v1/users/42"
new URL("/users/42", "https://api.example.com/v1/").href; // "https://api.example.com/users/42"

A leading / on the relative part drops the base path entirely. Most "why is my API client hitting the wrong version" bugs are one of these three lines.

Other languages pick different defaults

The same distinction between a path piece and a form value shows up everywhere, with different names and defaults. Python is the one that surprises people most. We checked these on Python 3.14:

python
>>> from urllib.parse import quote, quote_plus, urlencode
>>> quote("a b/c?d=é&~")
'a%20b/c%3Fd%3D%C3%A9%26~'
>>> quote("a b/c?d=é&~", safe="")
'a%20b%2Fc%3Fd%3D%C3%A9%26~'
>>> quote_plus("a b/c?d=é&~")
'a+b%2Fc%3Fd%3D%C3%A9%26~'
>>> urlencode({"q": "fish & chips", "r": "a/b"})
'q=fish+%26+chips&r=a%2Fb'
  • quote defaults to safe='/' because the docs intend it for the path section. Use it on a single value and slashes leak through unescaped. Pass safe="" for a component.
  • quote_plus and urlencode use form encoding: + for spaces, / escaped. requests does the same with its params= argument.
  • Since Python 3.7, ~ is treated as unreserved and left alone, matching RFC 3986.

Go splits it the same way: url.PathEscape escapes / for use inside one path segment, url.QueryEscape is for query values, and the net/url docs note that PathUnescape differs from QueryUnescape only in not turning + into a space. Whatever the language, find out whether a function means "path" or "form" before you trust it with a value.

Non-ASCII paths and international domain names

Paths, queries and fragments carry non-ASCII text as percent-encoded UTF-8. Hostnames can't: DNS predates Unicode, so internationalized domain names are converted to an ASCII form called Punycode, prefixed with xn--. The URL parser does both conversions for you:

js
new URL("https://münchen.de/straße?q=é").href;
// "https://xn--mnchen-3ya.de/stra%C3%9Fe?q=%C3%A9"

new URL("https://例え.jp/").host; // "xn--r8jz45g.jp"

Hosts and paths follow different rules, and encodeURI doesn't know about hosts at all. It percent-encodes them like any other text:

js
encodeURI("https://münchen.de/"); // "https://m%C3%BCnchen.de/"   (not a usable hostname)

In Node, url.domainToASCII("münchen.de") and url.domainToUnicode("xn--mnchen-3ya.de") convert a bare hostname in either direction, and Python's "münchen.de".encode("idna") gives b'xn--mnchen-3ya.de'. Don't mix converters, though. Python's built-in codec implements the older IDNA 2003 rules, and some characters convert differently under the newer rules browsers use:

text
Python  "straße.de".encode("idna")       b'strasse.de'
Node    url.domainToASCII("straße.de")    xn--strae-oqa.de
Node    new URL("https://straße.de/").host  xn--strae-oqa.de

Those are two different domains. If you validate, compare or allow-list hostnames, normalize them with the same parser your HTTP client uses.

A short checklist

  • Build URLs with URL and searchParams. Never interpolate raw values into a URL string.
  • Path segments go through encodeURIComponent, one segment at a time.
  • encodeURI is for tidying a complete URL a human typed. It doesn't protect values.
  • Encode once, at the boundary. %25XX in a log means something encoded twice.
  • Validate after the final decode, and wrap decoding of untrusted input in try.
  • Know which side expects + and which expects %20, especially for signed URLs.

Try it: the utilyx URL encoder switches between component and full-URL modes, + or %20 for spaces, and a strict RFC 3986 option. It points to the exact position of a broken % escape, which is usually the quickest way to find out which layer mangled a URL. It doesn't parse a URL into parts. For that, use the URL parser.

Try the URL encoder
Free, no sign-up, and it runs in your browser.
Open the tool →