A single unencoded & in a query parameter value can silently break your entire query string. A missing %2F in a redirect URI fails your OAuth flow. URL encoding bugs are notoriously hard to spot and debug — this guide makes sure you understand them completely.
Why URL Encoding Exists
URLs can only contain a limited set of characters defined by RFC 3986: letters, digits, and a few symbols (-._~). All other characters — including spaces, non-ASCII characters, and reserved delimiters — must be percent-encoded: replaced with a % followed by two hex digits representing the byte value.
Space → %20
& → %26
= → %3D
/ → %2F
? → %3F
# → %23
@ → %40
+ → %2B (in path/header context)
€ → %E2%82%AC (UTF-8 multi-byte)
encodeURIComponent vs encodeURI
JavaScript provides two functions and choosing the wrong one is a common mistake:
| Function | Does NOT encode | Use for |
|---|---|---|
encodeURIComponent | Letters, digits, -_.!~*'() | Individual parameter values |
encodeURI | All of above + /:@?= etc. | Complete URLs (preserves structure) |
// WRONG — encodeURI doesn't encode & so it breaks the param boundary
encodeURI("name=Alice & Bob") // → "name=Alice%20&%20Bob"
// CORRECT — encodeURIComponent encodes & so the value is safe
"name=" + encodeURIComponent("Alice & Bob") // → "name=Alice%20%26%20Bob"
// Building a query string correctly
var params = new URLSearchParams({ name: "Alice & Bob", age: "30" });
"https://api.example.com/users?" + params.toString();
new URLSearchParams(obj).toString() instead of manually encoding query strings. It handles all edge cases correctly and is available in all modern browsers and Node.js.URL Encoding in OAuth and Redirects
OAuth 2.0 and OIDC redirect URIs must be percent-encoded when included as a query parameter value. This is one of the most frequent OAuth implementation bugs:
// BROKEN — the redirect_uri contains unencoded = and &
https://auth.example.com/authorize?client_id=123&redirect_uri=https://app.com/callback?foo=bar
// CORRECT — redirect_uri value is fully encoded
https://auth.example.com/authorize?client_id=123&redirect_uri=https%3A%2F%2Fapp.com%2Fcallback%3Ffoo%3Dbar
+ vs %20 for Spaces
This causes constant confusion. The + sign represents a space only in the application/x-www-form-urlencoded format (HTML form submissions). In paths and modern REST APIs, spaces must be %20. Servers following RFC 3986 must treat + as a literal plus sign in query strings.
| Context | Space encoding |
|---|---|
| HTML form POST body | + |
| URL query string (modern) | %20 |
| URL path | %20 |
Decoding — Watch the Double-Encode Trap
Never encode an already-encoded string. %2520 is a double-encoded space (%25 is %, then 20). When parsing input, decode exactly once. Use the Parse URL tab in the Dev Cosmos tool to safely break a URL into its components and see decoded values side by side.