URL encoding bugs are quiet: everything works until a user has an ampersand in their name. The classics:
1. encodeURI vs encodeURIComponent
encodeURI keeps characters like / ? & = intact, so it's for whole URLs. encodeURIComponent escapes them, so use it for each query value. Using the wrong one either breaks the query string or double-handles it.
2. Double encoding
Encoding an already-encoded value turns %20 into %2520. Encode exactly once, at the boundary where you build the URL.
3. Plus versus %20
In application/x-www-form-urlencoded a space is +. In a URL path it must be %20. URLSearchParams uses +; encodeURIComponent uses %20. Know which your server expects.
4. Unicode needs UTF-8 first
é becomes %C3%A9 because it's percent-encoded as UTF-8 bytes. Legacy Latin-1 decoders will show garbage.
5. Don't hand-concatenate query strings
Use new URL() and url.searchParams.set(k, v). It handles escaping and duplicate keys consistently.
6. Open redirects
Never trust a decoded ?next= value; validate against an allowlist after decoding.
Debugging
To see what a mangled URL really contains I use a local URL encoder/decoder, which runs in the browser so nothing is sent anywhere.
Disclosure: I built WebDevToolbox, a free collection of 500+ browser-based dev tools.
Top comments (1)
The %20 turning into %2520 thing bites everyone at least once. Encoding once at the point where the URL is built is the simplest rule.