URL Encoding: 6 Mistakes That Break Your Query Strings
Broken links and missing query parameters are often an encoding problem. These are the mistakes worth knowing. 1. encodeURI vs encodeURIComponent encodeURI leaves ? & = # alone, so it is for whole URLs. encod
Broken links and missing query parameters are often an encoding problem. These are the mistakes worth knowing.
1. encodeURI vs encodeURIComponent
encodeURI leaves ? & = # alone, so it is for whole URLs. encodeURIComponent encodes them, so it is for individual values. Using the wrong one either breaks the URL or the value.
2. Double encoding
Encoding an already encoded value turns %20 into %2520. Encode once, at the last step before sending.
3. Plus vs %20
In form data + means space, but in a URL path it is a literal plus. Mixing them silently changes your data.
4. Unicode and emoji
Non-ASCII characters are encoded as UTF-8 bytes, so one emoji becomes up to 12 characters. Check length limits after encoding.
5. Forgetting to encode user input
Putting raw input in a query string lets & and # inject extra parameters. Use URLSearchParams so it is handled for you.
const p = new URLSearchParams({ q: "a&b=c" });
`/search?${p}` // /search?q=a%26b%3Dc
6. Decoding too early
Decode only after you split the query string, otherwise an encoded & is treated as a separator.
Handy tools
For debugging I use the URL encoder/decoder and URL parser, both free and client-side, from webdevtoolbox.com.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.