Ctrl + K
URLs19 min read

When to Use URL Encoding

A practical guide to URL encoding, covering percent-encoding, reserved and unreserved characters, query parameters, URL paths, fragments, JavaScript APIs, common mistakes and security considerations.

Published: 2026-10-05

URLs look simple when they contain only letters, numbers and a few familiar punctuation characters. Problems start when a URL needs to contain spaces, non-ASCII characters, reserved symbols or user-provided data. This is where URL encoding becomes important.

URL encoding, more precisely percent-encoding, converts characters into a representation that can safely appear in a URL component. It is commonly used for query parameters, form values, paths and other places where characters could otherwise be interpreted as URL syntax.

The important part is knowing when to encode. Encoding an entire URL indiscriminately can be just as problematic as failing to encode user-provided data. Different URL components have different rules, so the correct approach is usually to encode the individual value before placing it into the appropriate part of the URL.

What Is URL Encoding?

URL encoding represents characters using a percent sign followed by two hexadecimal digits. For example, a space can be represented as %20.

Hello World
Hello%20World

The encoded form allows the value to travel through URL syntax without the space being interpreted as an invalid or ambiguous character.

The term URL encoding is widely used by developers, although percent-encoding is the more precise technical description. Not every character needs to be percent-encoded. Some characters are considered safe in particular URL components, while others have special structural meaning.

When Should You Use URL Encoding?

The most common rule is simple: encode data that you are inserting into a URL component when that data may contain characters that have special meaning or cannot safely appear there.

  • Encoding query parameter names and values.
  • Encoding user-entered text placed into a URL.
  • Encoding non-ASCII characters when constructing URL components.
  • Encoding values containing reserved characters such as &, = or ?.
  • Encoding path segments when their contents are dynamic.
  • Encoding fragment values when necessary.
  • Encoding data before placing it into a URL generated by application code.

You generally should not encode the entire URL as though it were one ordinary string. The URL itself contains structural delimiters such as :, /, ?, # and &, and those characters may need to remain meaningful to the URL parser.

A Simple Query Parameter Example

Suppose an application needs to send a search query containing spaces.

https://example.com/search?q=hello world

The value should be encoded before being inserted into the query string.

https://example.com/search?q=hello%20world

The important distinction is that only the value hello world needed encoding. The scheme, host, path and query delimiters remain part of the URL structure.

Why Not Encode the Whole URL?

A common mistake is passing a complete URL to a generic component encoder. That can encode characters that are supposed to define the URL structure.

https://example.com/search?q=hello world

If the complete string is encoded as one value, characters such as : and / can become percent-encoded as well. The resulting string no longer represents the same URL structure when used where a URL is expected.

⚠️ Encode URL components, not an already assembled URL. Build the URL from structured parts and encode dynamic values according to the component they belong to.

Reserved Characters

Some characters have special meaning in URL syntax. These are commonly called reserved characters because they can delimit or structure different parts of a URL.

CharacterTypical meaningWhy encoding may be needed
?Starts the query componentNeeded when ? is part of a value rather than URL syntax
&Separates query parametersNeeded when & belongs inside a parameter value
=Separates parameter name and valueNeeded when = is part of a value
#Starts the fragmentNeeded when # belongs inside data
/Separates path segmentsMay need encoding when / belongs inside one segment
%Introduces percent-encodingShould be encoded when it is literal data

Whether a reserved character must be encoded depends on where it appears. A question mark can be structural in one location and ordinary data in another. URL encoding therefore has to be considered at the component level.

Unreserved Characters

URL syntax defines a set of characters known as unreserved characters. These can generally appear without percent-encoding.

A-Z a-z 0-9 - . _ ~

These characters are generally safe because they do not have structural meaning in the same way as reserved delimiters.

💡 You do not need to percent-encode every character simply because encoding is available. Encode characters when required by URL syntax, the specific component, or the API receiving the value.

Spaces in URLs

Spaces are one of the most common reasons developers encounter URL encoding. A literal space is not normally represented directly in a URL, so it needs an appropriate encoded representation.

Hello World
Hello%20World

When working specifically with application/x-www-form-urlencoded form data, spaces may instead be represented using +. This is a related but distinct convention from general percent-encoding.

q=hello+world

This distinction matters when manually constructing or parsing query strings. APIs and frameworks often handle form encoding automatically, but custom code should not assume that + and %20 are interchangeable in every URL-processing context.

Encoding Query Parameters

Query parameters are probably the most common place where developers need URL encoding. A query parameter is data, while characters such as ? and & provide the surrounding structure.

https://example.com/search?q=red shoes&sort=price

The search value should be encoded because it contains a space, while the & separating parameters remains structural.

https://example.com/search?q=red%20shoes&sort=price

Why Query Parameter Values Must Be Encoded

Consider a value containing an ampersand.

filter=rock&roll

If this is intended to be one parameter value, the ampersand cannot remain unencoded because the URL parser can interpret it as the beginning of another parameter.

filter=rock%26roll

Now the ampersand is part of the filter value rather than a query-string delimiter.

Encoding Query Parameter Names

Parameter names are also data and can require encoding. In most APIs, parameter names contain only simple ASCII characters, so this is rarely noticeable. Generic URL-building code should nevertheless treat both names and values as components rather than concatenating arbitrary strings.

const params = new URLSearchParams();

params.set("search term", "red shoes");
params.set("page", "2");

const url = `https://example.com/search?${params.toString()}`;

Using a dedicated URL API avoids many manual escaping errors because the API understands that these strings are query parameter names and values.

URLSearchParams and Query Encoding

In JavaScript, URLSearchParams is one of the safest and simplest ways to construct query parameters.

const params = new URLSearchParams({
  q: "red shoes",
  category: "men's shoes",
});

const url = `https://example.com/search?${params.toString()}`;

console.log(url);

The API handles the appropriate serialization instead of requiring manual calls to encodeURIComponent for every value.

encodeURIComponent vs encodeURI

JavaScript provides two commonly used functions for URL-related encoding: encodeURI and encodeURIComponent. They are not interchangeable.

FunctionIntended useTypical input
encodeURIEncoding a URI while preserving URI structureA complete URI or URL
encodeURIComponentEncoding one URI componentA query value, path segment or other dynamic component

For application code that inserts user-provided text into a query parameter, encodeURIComponent is usually the more relevant primitive.

const search = "red shoes & boots";
const encoded = encodeURIComponent(search);

console.log(encoded);

The result can then be placed into the appropriate URL component.

When to Use encodeURI

encodeURI is designed for a complete URI and intentionally preserves characters that have structural meaning in a URI, such as the separators between its components.

const url = "https://example.com/search?q=red shoes";
const encodedUrl = encodeURI(url);

Even so, building URLs from structured components is generally clearer and less error-prone than assembling a complete URL string and encoding it afterward.

When to Use encodeURIComponent

encodeURIComponent is intended for an individual component rather than an entire URL. Typical examples include query values and dynamically generated path segments.

const username = "John & Jane";

const url =
  `https://example.com/users/${encodeURIComponent(username)}`;

Here the username is data. The / characters that define the URL structure are not part of the value and therefore should not be encoded together with it.

URL Encoding in Path Segments

URL paths can also contain dynamic data. If an application uses a user-provided value as one path segment, that value should be encoded as a component before being inserted.

https://example.com/files/my%20document.pdf

The encoded space is part of the filename segment. The slash separating /files/ from the filename remains structural.

Why Path Segments Need Special Attention

The slash character is significant in paths. If a dynamic value is supposed to represent one segment but contains a slash, leaving it unencoded can turn one segment into several segments.

Value: reports/2026
Encoded value: reports%2F2026

Whether the slash should be encoded depends on the application's intended semantics. If reports/2026 is supposed to represent two path segments, the slash should remain structural. If it is supposed to be one identifier, encoding the slash preserves it as data.

URL Encoding and Fragments

A fragment begins with # and is interpreted by the client rather than sent to the server as part of the HTTP request. Dynamic fragment values can still require encoding when they contain characters that have special meaning within the fragment.

https://example.com/docs#section%202

For application-controlled fragments, it is often useful to treat the fragment as its own component instead of encoding the complete URL.

Encoding Non-ASCII Characters

URLs may need to represent text written in languages other than English. Unicode characters can be represented in URLs using percent-encoded UTF-8 bytes.

https://example.com/search?q=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82

The encoded sequence represents the UTF-8 bytes of the original Cyrillic text. Modern URL APIs handle this conversion automatically in many cases.

💡 Do not manually convert Unicode text into percent-encoded bytes unless you have a specific reason. Prefer URL, URLSearchParams and related platform APIs so UTF-8 handling is performed consistently.

Internationalized Domain Names Are Different

Encoding a path or query value is not the same operation as handling an internationalized domain name. Domain names use their own representation mechanisms, including Punycode through the internationalized domain name system.

For example, a domain containing non-ASCII characters should not simply be treated as an ordinary query parameter and passed through encodeURIComponent. URL parsing libraries and browser URL APIs understand the different roles of the hostname and other URL components.

URL Encoding and Form Data

HTML forms commonly use the application/x-www-form-urlencoded format when submitting form data. This format is closely related to URL query encoding and is one reason developers encounter + as a representation of spaces.

name=John+Doe&city=New+York

When using browser APIs such as URLSearchParams, the serialization rules are handled by the platform. This is preferable to manually replacing spaces and special characters.

URL Encoding vs HTML Encoding

URL encoding and HTML encoding solve different problems. URL encoding represents data safely within URL syntax, while HTML encoding represents characters safely within HTML markup.

EncodingPurposeExample
URL encodingRepresent data inside URL syntax%20
HTML encodingRepresent special characters in HTML&
Base64Represent binary data as textSGVsbG8=
JSON escapingRepresent strings safely in JSON\"

These transformations should not be substituted for one another. A string may pass through multiple formats in a web application, and each layer has its own escaping rules.

Double URL Encoding

Double encoding occurs when a value that has already been percent-encoded is encoded again.

Original: Hello World
Encoded once: Hello%20World
Encoded again: Hello%2520World

The second encoding changes the percent sign in %20 into %25. If the server decodes only once, it receives Hello%20World rather than Hello World.

⚠️ Avoid encoding a value before passing it to an API that will encode it for you. Double encoding is a common source of broken query parameters and unexpected route values.

How Double Encoding Happens

  • Calling encodeURIComponent on a value that is already encoded.
  • Manually constructing an encoded query string and then passing it to URLSearchParams.
  • Encoding a URL before handing it to an API that expects an ordinary URL.
  • Encoding server output again before returning it to the client.
  • Mixing multiple libraries that each assume responsibility for encoding.

Decoding URL-Encoded Data

Decoding reverses percent-encoding when the encoded value needs to be interpreted as its original data.

const encoded = "hello%20world%20%26%20more";
const decoded = decodeURIComponent(encoded);

console.log(decoded);

As with encoding, decoding should happen at the correct layer. A component should not be decoded repeatedly simply because a value contains percent signs.

Do Not Decode Arbitrary URLs Repeatedly

A complete URL is a structured object, not simply an encoded string. Repeatedly applying decodeURIComponent to arbitrary input can produce errors or alter data that was intentionally encoded.

When working with URLs in JavaScript, it is generally safer to parse the URL into components and work with the relevant property rather than repeatedly applying generic string transformations.

Use the URL API Instead of String Concatenation

Modern JavaScript provides the URL API for constructing and parsing URLs. It separates the URL into meaningful components and reduces the need for manual string manipulation.

const url = new URL("https://example.com/search");

url.searchParams.set("q", "red shoes & boots");
url.searchParams.set("page", "2");

console.log(url.toString());

This approach is generally easier to maintain than manually joining ?, &, = and encoded values.

URL Encoding in APIs

APIs frequently use query parameters and path parameters to receive data from clients. Correct encoding ensures that the server receives the intended values rather than interpreting data characters as URL delimiters.

https://api.example.com/products?search=red%20shoes&category=summer

Frameworks and HTTP clients often provide helpers for this. Using those helpers is preferable to manually constructing query strings whenever possible.

URL Encoding in React and Next.js

React and Next.js applications commonly create URLs for search pages, filters, pagination, dynamic routes and navigation. User-controlled values should be treated as data and encoded through URL-aware APIs.

const params = new URLSearchParams();

params.set("query", searchQuery);
params.set("category", category);

const href = `/search?${params.toString()}`;

This is particularly useful for search interfaces because users can enter spaces, punctuation and non-ASCII text without the application having to manually calculate the correct percent-encoded representation.

Encoding User-Provided Data

Any time user input becomes part of a URL, consider the input a data value rather than URL syntax. This applies to search terms, usernames, product names, document names, filters, tags and other dynamic values.

Encoding protects the URL structure from being confused with the user's data. It does not replace validation or authorization. A correctly encoded malicious value is still malicious data if the application uses it unsafely on the server or in another context.

URL Encoding Is Not Security Encryption

Percent-encoding does not hide information. Anyone can decode a percent-encoded value, and browsers routinely decode URL components as part of normal URL processing.

secret%3D12345
secret=12345

The encoded form is only another representation of the same data. Never use URL encoding as a mechanism for protecting passwords, API keys, tokens or other secrets.

⚠️ Do not put sensitive secrets into URLs simply because they are URL-encoded. URLs can appear in browser history, logs, analytics systems, proxy logs, referrers and other places.

URL Encoding and XSS

URL encoding can help preserve URL structure, but it is not a complete XSS defense. A value that is safe in one context may become dangerous after being decoded and inserted into HTML, JavaScript or another interpreter.

The correct defense is context-specific output encoding, validation and safe APIs. URL encoding should be used for URL components, while HTML and JavaScript contexts require their own appropriate handling.

URL Encoding and Path Traversal

Encoded path characters can also matter to security. A value such as %2F represents a slash byte when decoded, and servers, proxies and frameworks may process encoded paths differently.

Applications handling filesystem paths or authorization-sensitive routes should normalize and validate paths rather than assuming that URL encoding alone prevents traversal or access-control problems.

Common URL Encoding Mistakes

  • Encoding an entire URL instead of an individual component.
  • Failing to encode query parameter values.
  • Leaving an ampersand unencoded inside a query value.
  • Using encodeURI when encodeURIComponent is needed.
  • Using encodeURIComponent on an already encoded value.
  • Manually replacing spaces instead of using URL APIs.
  • Confusing URL encoding with HTML escaping.
  • Treating URL encoding as encryption.
  • Assuming every percent-encoded value should be decoded immediately.
  • Ignoring differences between URL components.

A Better URL Construction Pattern

Instead of constructing a URL through repeated string concatenation, start with a structured URL and modify its components.

const url = new URL("https://example.com/products");

url.searchParams.set("search", "red shoes & boots");
url.searchParams.set("page", "2");
url.searchParams.set("sort", "price");

console.log(url.toString());

The browser's URL implementation handles the serialization of the query parameters. This reduces the amount of encoding logic that application code has to maintain.

When Manual Encoding Still Makes Sense

There are situations where explicit percent-encoding is useful. You may be implementing a low-level protocol, generating a URL for a system that expects a specific representation, debugging an encoding problem, or working with an API that requires an individual encoded component.

In those cases, component-level functions such as encodeURIComponent can be appropriate. The key is to know exactly which component is being encoded and whether another layer will encode it again.

URL Encoding Checklist

  • Identify which URL component contains the dynamic value.
  • Treat user input as data, not as URL syntax.
  • Encode query parameter names and values when constructing them manually.
  • Encode dynamic path segments when necessary.
  • Use encodeURIComponent for individual components.
  • Prefer URL and URLSearchParams for normal application code.
  • Do not encode the complete URL indiscriminately.
  • Avoid double encoding.
  • Do not confuse URL encoding with HTML escaping or encryption.
  • Do not place secrets into URLs just because they are encoded.

Frequently Asked Questions

When should I use URL encoding?

Use URL encoding when inserting data into a URL component and that data contains characters that have special meaning in URL syntax or cannot safely appear there. Query parameters and dynamic path segments are common examples.

Should I encode the entire URL?

Usually no. Encode the individual component that contains dynamic data. Encoding the complete URL can also encode structural characters such as :, /, ? and &, changing how the URL is interpreted.

Should I use encodeURI or encodeURIComponent?

encodeURI is intended for a complete URI while preserving its structural characters. encodeURIComponent is intended for an individual component such as a query parameter value or dynamic path segment.

Why does a space become %20?

Percent-encoding represents a character using % followed by its hexadecimal byte representation. A space is commonly represented as %20 in URL components.

Why do some query strings use + for spaces?

The application/x-www-form-urlencoded format commonly represents spaces with +. This is a form/query serialization convention and is different from general percent-encoding, where a space is commonly represented as %20.

Can URL encoding protect sensitive information?

No. URL encoding is reversible and provides no confidentiality. It should never be treated as encryption or used to protect passwords, API keys, access tokens or other secrets.

How can I avoid double URL encoding?

Keep values unencoded while they are being manipulated and let the URL or query-string API encode them at serialization time. Avoid passing an already percent-encoded value into another encoder.

Helpful URL Encoding Tools

A URL Encoder / Decoder is useful when you need to inspect how a particular value changes after percent-encoding or decoding. A URL Builder can help assemble URLs from their components, while a URL Parser is useful for examining an existing URL and separating its scheme, host, path, query and fragment. For query strings specifically, a Query Parameter Builder can construct encoded parameters without manual concatenation, and a Query Parameter Decoder can help inspect encoded query values when debugging API requests or links.

Conclusion

URL encoding is primarily about preserving the distinction between URL structure and URL data. Characters such as &, =, ?, # and / can have structural meaning, so dynamic values containing those characters may need to be percent-encoded before they are inserted into the appropriate component.

The most important practical rule is to encode components rather than blindly encoding complete URLs. For query parameters and dynamic values, URLSearchParams, the URL API and component-level encoding functions can eliminate many common mistakes.

Finally, remember that URL encoding is neither encryption nor a general security mechanism. It is a representation technique. Used at the correct layer, it makes URLs reliable and unambiguous; used indiscriminately, it can produce broken URLs, double encoding and difficult-to-debug application behavior.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.