URL encoding is one of those things that works silently until it doesn't. You paste a link with a space in it, or you build a query string by hand, and suddenly your API returns a 400 or your route matches the wrong thing. Understanding what's happening under the hood saves a lot of debugging time.
What URL encoding actually is
URLs can only safely contain a limited set of ASCII characters. Letters, digits, and a handful of symbols like -, _, ., and ~ are allowed as-is. Everything else — spaces, slashes in the wrong place, ampersands, non-ASCII text — has to be represented differently.
URL encoding (also called percent-encoding) replaces unsafe characters with a % followed by two hexadecimal digits representing the byte. A space becomes %20. An ampersand becomes %26. The letter é, encoded as UTF-8, becomes %C3%A9 — two bytes, two percent sequences.
That last point matters: percent-encoding operates on bytes, not characters. For anything outside ASCII you first encode the text as UTF-8, then percent-encode each byte. Get the character set wrong and you'll see mojibake on the other end.
When you need it
You need encoding any time user data or arbitrary values end up inside a URL. The common cases:
- Query string values — search terms, filter parameters, anything a user types.
- Path segments that contain dynamic data, like a username or a file name with spaces.
- Form submissions using
application/x-www-form-urlencoded, where the whole body is encoded key/value pairs. - Redirect targets passed as a parameter, e.g.
?return_to=..., which must be encoded so their own query string doesn't leak into the parent URL.
The classic failure is building a search link like /search?q=black & white. That space breaks the URL and the & gets read as a parameter separator. Encoded, it becomes /search?q=black%20%26%20white and everything behaves.
Encode vs decode the right component
A URL has parts with different rules, and that trips people up constantly. A slash is legal in a path but needs encoding inside a single path segment. Most languages give you two functions for this reason.
In JavaScript:
// Encodes a whole URL but leaves :/?#[]@!$&'()*+,;= intact
encodeURI('https://example.com/a b?x=1');
// -> "https://example.com/a%20b?x=1"
// Encodes a single value, including reserved characters
encodeURIComponent('black & white');
// -> "black%20%26%20white"Rule of thumb: use encodeURIComponent for individual pieces — a single query value or path segment. Use encodeURI only when you have a full URL that's mostly correct and just needs stray characters cleaned up. If you're ever unsure, encode the component.
Common gotchas
Double encoding
Encode a string that's already encoded and %20 becomes %2520 — the % itself gets escaped. This shows up when a value passes through multiple layers that each helpfully encode it. Symptoms: literal %20 appearing in rendered text, or parameters that look encoded twice. Decode once and check before encoding again.
The plus-sign ambiguity
In the query string of a form-encoded request, + historically means a space. But %20 also means a space. In the path, + is a literal plus. So encodeURIComponent(' ') gives you %20, while many server form parsers emit +. If you're decoding a query string manually, decide which convention you're following. Mixing them means spaces turn into pluses or vice versa.
Spaces aren't the only problem
People remember to encode spaces and forget the rest. Characters like # (fragment delimiter), ?, &, =, /, and + all have special meaning and will silently corrupt your URL if left raw in a value.
Not everything should be encoded
Don't blanket-encode a whole URL you're constructing from parts, because you'll clobber the structural characters. Encode the values, then assemble. Build the URL, encode the pieces.
A worked example
Say you're constructing a link to an external map service with a search query and a callback URL. Here's the naive, broken version:
const q = 'Café René, Paris';
const back = 'https://myapp.com/results?sort=name&page=2';
const bad = `https://maps.example.com/search?q=${q}&return=${back}`;
// q has a comma, accent, and spaces; back has its own ?, &, =
// The parser will see sort/page/return as top-level params. Chaos.The fixed version encodes each value independently:
const url = `https://maps.example.com/search?q=${encodeURIComponent(q)}`
+ `&return=${encodeURIComponent(back)}`;
// -> https://maps.example.com/search
// ?q=Caf%C3%A9%20Ren%C3%A9%2C%20Paris
// &return=https%3A%2F%2Fmyapp.com%2Fresults%3Fsort%3Dname%26page%3D2Notice how the entire return URL is now a single opaque value — its ?, &, and = are escaped, so the maps service receives exactly two parameters, q and return. On the receiving end a single decodeURIComponent restores the original.
A cleaner approach in the browser avoids manual string building entirely:
const u = new URL('https://maps.example.com/search');
u.searchParams.set('q', q);
u.searchParams.set('return', back);
console.log(u.toString());The URL and URLSearchParams APIs handle encoding for you and are far less error-prone than template strings. Reach for them when you can.
Quick verification
When something looks wrong, the fastest fix is to paste the string somewhere and see the encoded and decoded forms side by side. I keep the URL Encoder / Decoder open for exactly this — it's handy for spotting double encoding, confirming how a weird character maps to its byte sequence, and sanity-checking a value before it goes into a request.
The short version
- Encode values, not whole structured URLs.
- Prefer
encodeURIComponentfor individual parts. - Watch for double encoding and the
+/%20space ambiguity. - Use
URL/URLSearchParamsto build links so encoding happens correctly by default.
Get those right and the mysterious 400s and broken redirects mostly disappear.
Photo by Chris Ried on Unsplash