How to Avoid Double URL Encoding
Double encoding is one of the most frustrating bugs in web development. It occurs when a string that has already been percent-encoded is passed through an encoder a second time.
The Anatomy of Double Encoding
Let's look at how this happens:
- You start with a space:
- You encode it once: The space becomes
%20 - You accidentally encode it again: The percent sign (
%) is a reserved character, so the encoder translates the%into%25. - The final output is
%2520.
When the server decodes %2520, it translates it back into %20, not a space. Your database query or application logic will likely fail because it is looking for a string containing a space, not the literal text "%20".
How to Prevent It
- Know Your Framework: Many modern HTTP clients (like Axios) and URL builders automatically encode parameters. If you manually run
encodeURIComponentbefore passing the data to the library, you will cause double encoding. - Check the Input: If you are unsure whether a string is already encoded, you can attempt to decode it first. If
decodeURIComponent(str) === str, the string was not encoded. - Centralize Encoding Logic: Ensure that encoding only happens at the absolute edge of your application—right before the string is concatenated into the final URL string.