Encoders

URL Encoding and Decoding: Percent-Encoding, RFC 3986, and Security

Deep dive into URL percent-encoding: RFC 3986 rules, the difference between encodeURI and encodeURIComponent, double-decoding risks, and URLSearchParams.

WebUtil Team

1. How Percent-Encoding Works Under RFC 3986

Uniform Resource Identifiers (URIs) are constrained by the Internet standard RFC 3986 to a limited subset of characters from the US-ASCII repertoire. When web applications need to transmit arbitrary binary data, punctuation, spaces, or international Unicode characters (such as emojis or accented letters) inside a URL, they must convert those characters into percent-encoding.

Percent-encoding represents any non-allowed byte as a triplet consisting of the percent symbol '%' followed by two hexadecimal digits denoting the byte value in ASCII (or UTF-8 for international characters). For example, a space character (ASCII 32, hex 0x20) is encoded as '%20', and an exclamation mark (ASCII 33, hex 0x21) is encoded as '%21'.

2. Reserved vs Unreserved Characters: When %20 Meets Plus (+)

RFC 3986 divides URI characters into two distinct classes:

  • Unreserved Characters: A-Z, a-z, 0-9, hyphen (-), underscore (_), period (.), and tilde (~). These characters never require percent-encoding and retain their literal meaning.
  • Reserved Characters: Characters with structural syntactic meaning inside a URI, including delimiters like ':', '/', '?', '#', '[', ']', '@', '!', '$', '&', ''', '(', ')', '*', '+', ',', ';', and '='.

A frequent source of confusion is the plus sign (+). Under historical HTML form submission specifications (application/x-www-form-urlencoded), spaces in form data were encoded as '+'. However, according to strict RFC 3986 URI path syntax, a plus sign literally represents '+' and not a space! Modern APIs should always use '%20' for spaces to avoid ambiguity.

3. The Critical Difference: encodeURI() vs encodeURIComponent()

In JavaScript, developers are provided two built-in global functions for percent-encoding, but using the wrong one can break URLs or introduce security flaws:

```javascript const baseUrl = 'https://webutil.tech/search'; const query = 'developer tools & utilities?';

// WRONG: encodeURI preserves '&' and '?' because it treats them as URI delimiters const badUrl = `${baseUrl}?q=${encodeURI(query)}`; // Result: https://webutil.tech/search?q=developer%20tools%20&%20utilities? // Breaks the query string because '&' creates a second parameter!

// CORRECT: encodeURIComponent encodes '&' to '%26' and '?' to '%3F' const goodUrl = `${baseUrl}?q=${encodeURIComponent(query)}`; // Result: https://webutil.tech/search?q=developer%20tools%20%26%20utilities%3F ```

  • Use `encodeURI()` ONLY when encoding an entire, complete URL where delimiters (http://, ?, &) must remain intact.
  • Use `encodeURIComponent()` whenever encoding a specific query parameter value or path segment.
Sponsored
Advertisement

4. The Double-Encoding Vulnerability in Reverse Proxies

Double-encoding occurs when a string that is already percent-encoded is mistakenly encoded a second time by an application or proxy layer. For example, a space (' ') becomes '%20' on the client, and an unconfigured reverse proxy (such as Nginx or Apache) re-encodes the '%' into '%2520'.


              Raw Character:   /
First Encoding:  %2F
Second Encoding: %252F
            

Double-encoding is not just an annoying formatting bug—it is an established web security attack vector. Malicious actors use double-encoded path traversal sequences (such as '%252e%252e%252f' for '../') to bypass Web Application Firewalls (WAFs). If the WAF decodes the string once and finds '%2e%2e%2f' (which it considers harmless text), but the backend server decodes it a second time, the attacker successfully traverses directories.

5. Modern Query String Handling with URLSearchParams

In modern JavaScript (Node.js and modern browsers), manually string-concatenating query strings with encodeURIComponent is deprecated in favor of the standard `URLSearchParams` and `URL` APIs:

```javascript const url = new URL('https://webutil.tech/api/search'); url.searchParams.set('query', 'client-side tools & privacy'); url.searchParams.set('page', '1'); url.searchParams.set('tags', 'security');

console.log(url.toString()); // Output: https://webutil.tech/api/search?query=client-side+tools+%26+privacy&page=1&tags=security

// Parsing an existing URL query const params = new URLSearchParams(window.location.search); const currentQuery = params.get('query'); // Automatically decodes percent-encoding! ```

6. Debugging Malformed URIs and Decoding Errors in Production

When decoding strings in JavaScript, `decodeURIComponent()` throws a fatal `URIError: URI malformed` if the string contains an invalid percent sequence (such as a '%' not followed by two hexadecimal digits, or an invalid UTF-8 byte sequence like '%E0%A4'). Always wrap decode operations in a try/catch block when handling untrusted user input.

WebUtil's URL Encoder / Decoder tool allows you to instantly encode and decode query strings, full URIs, and isolated components with real-time error detection entirely in your browser.