The Art of URL Building: Best Practices
How to build URLs with many query parameters safely, avoid encoding bugs, and use the right tools when debugging links.
URLs (Uniform Resource Locators) are the fundamental address system of the web. Constructing them seems simple until you have to deal with dynamic paths, multiple query parameters, port numbers, authentication credentials, and protocol variations.
Anatomy of a Complex URL
To build robust URLs, we must understand their component parts as defined in standard specifications:
- Scheme (Protocol):
http,https,ftp,ws. Always preferhttpsfor security. - Authority: Contains the user, password (deprecated but exists), host (domain), and port.
- Path: The hierarchical location of the resource.
- Query: Non-hierarchical data (parameters) starting with
?. - Fragment: Client-side anchor starting with
#. This is never sent to the server.
Common Pitfalls in Manual Construction
1. Double Encoding
Encoding an already encoded value is a frequent bug. If %20 becomes %2520, your links break. A string alone cannot tell you whether it is already encoded (a literal %20 could be data), so the reliable fix is to keep values raw and encode them once, in the layer that builds the URL.
2. The Trailing Slash Dilemma
Some servers treat /resource and /resource/ as different endpoints. Inconsistent slash handling leads to 301 Redirect loops or SEO duplicate content issues.
Best Practice: Decide on a convention and stick to it universally, redirecting the other form to it.
3. String Concatenation Hell
Using + to build URLs is dangerous.
// Risky
const url = base + "/" + path;
// If base ends with / and path starts with /: "base//path"This often results in double slashes // which servers and proxies may treat as a different path from the single-slash version (and, at the start of a reference, // means "protocol-relative", so a stray leading // can change the host entirely).
Protocol Relative URLs
A URL starting with // (e.g., //cdn.example.com/lib.js) tells the browser to "use the same protocol as the current page".
While useful historically to avoid mixed content warnings, today, just use https everywhere. Protocol relativity can mistakenly load insecure HTTP content if your base page is HTTP.
Security: Open Redirect Vulnerabilities
When building URLs based on user input (e.g., a "return to" parameter), you must validate the host. Failing to do so allows attackers to construct URLs that look legitimate but redirect users to phishing sites.
Query Parameter Best Practices
Parameter Order
While parameter order doesn't affect functionality, maintaining a consistent order improves readability and debugging:
- Sort alphabetically for consistency
- Group related parameters together
- Place required parameters before optional ones
URL Length Limits
The URL syntax has no length limit, but software does. Some reference points:
- HTTP specification: RFC 9110 recommends that all senders and recipients support URIs of at least 8,000 octets. That is a floor for interoperability, not a ceiling.
- Internet Explorer: 2,083 characters, per Microsoft's own documentation (IE support ended in June 2022).
- Apache httpd: the request line, which includes the URI, is limited by
LimitRequestLine, default 8,190 bytes. - nginx: the request line must fit in one buffer of
large_client_header_buffers, default 8 KB, otherwise it answers with a 414 error. - Current Chrome and Firefox: far higher (on the order of megabytes), so the browser is rarely the bottleneck. Proxies, CDNs, and servers in the path usually are.
For complex data, prefer POST requests with JSON bodies instead of long query strings.
URL Building in Different Languages
JavaScript/TypeScript
const url = new URL('/path', 'https://example.com');
url.searchParams.set('key', 'value');
console.log(url.toString());
Python
from urllib.parse import urlencode, urlunparse
params = {'key': 'value'}
query = urlencode(params)
url = urlunparse(('https', 'example.com', '/path', '', query, ''))
Joining Base URLs and Paths Correctly
The second argument of the URL constructor is a base, and the result follows the same relative-resolution rules a browser applies to links. That makes it the right tool for joining, but the rules have sharp edges around trailing slashes and leading slashes:
const base = "https://api.example.com/v1/";
new URL("users", base).href
// "https://api.example.com/v1/users"
new URL("/users", base).href
// "https://api.example.com/users" (leading slash discards /v1/)
new URL("users", "https://api.example.com/v1").href
// "https://api.example.com/users" (no trailing slash: "v1" is replaced)
"https://api.example.com/v1/" + "/" + "/users"
// "https://api.example.com/v1///users" (string concatenation)If your API base contains a path prefix, normalize it once (always with a trailing slash) and always pass relative references without a leading slash. Alternatively, build the path explicitly from segments as shown below.
Encoding Path Segments, Not Just Query Values
Query parameters get most of the attention, but dynamic path segments need the same care. A user-supplied ID or filename containing / or ? changes the structure of the URL unless it is encoded:
const seg = "reports/2025 Q1?.pdf";
new URL("/files/" + seg, "https://example.com").href
// "https://example.com/files/reports/2025%20Q1?.pdf"
// -> the ? started a query string and the / added a path level
new URL("/files/" + encodeURIComponent(seg), "https://example.com").href
// "https://example.com/files/reports%2F2025%20Q1%3F.pdf"Setting url.pathname directly does not save you here: it encodes spaces, non-ASCII characters, ?, and #, but treats / as a separator. Encode each segment individually with encodeURIComponent before joining with /. The server must of course decode %2F as data and not as a path separator, and some servers and proxies reject or rewrite encoded slashes, so avoid slashes in IDs where you can.
A Reusable URL Builder Function
Putting the rules together, this helper joins a base, encodes each path segment, appends parameters (repeating keys for arrays, skipping null and undefined), and sets an optional fragment. The output shown is what it actually returns:
function buildUrl(base, segments, params = {}, hash = "") {
const u = new URL(base);
u.pathname = u.pathname.replace(/\/+$/, "") + "/" + segments.map(encodeURIComponent).join("/");
for (const [key, value] of Object.entries(params)) {
if (value == null) continue;
if (Array.isArray(value)) value.forEach((v) => u.searchParams.append(key, v));
else u.searchParams.set(key, value);
}
if (hash) u.hash = hash;
return u.toString();
}
buildUrl("https://api.example.com/v1", ["users", "jane doe", "posts"],
{ page: 2, tag: ["a&b", "c"], q: "C++", skip: undefined }, "top");
// "https://api.example.com/v1/users/jane%20doe/posts?page=2&tag=a%26b&tag=c&q=C%2B%2B#top"Note the q=C%2B%2B: searchParams encodes the plus signs so they survive a form-style parser. If your array format is not repeated keys, see JSON to Query String for the alternatives.
Modifying Existing URLs Without Surprises
Editing a URL that already has a query is where URLSearchParams behavior surprises people. Any mutation re-serializes the entire query string using form-urlencoding, so previously valid encodings can change form even though they mean the same thing:
const x = new URL("https://example.com/?q=a%20b&r=%7E");
x.searchParams.append("z", "1");
x.href
// "https://example.com/?q=a+b&r=%7E&z=1" (%20 became +)
const u = new URL("https://example.com/s?utm_source=x&b=2&a=1&utm_medium=y");
u.searchParams.sort();
u.search
// "?a=1&b=2&utm_medium=y&utm_source=x"
for (const k of [...u.searchParams.keys()]) {
if (k.startsWith("utm_")) u.searchParams.delete(k);
}
u.href
// "https://example.com/s?a=1&b=2"Sorting parameters and stripping tracking keys is a cheap way to produce a canonical URL for caching keys, deduplication, or comparing links. Copy the keys into an array before deleting, as above, because deleting while iterating the live iterator skips entries. If a signed URL depends on the exact original query bytes, do not round-trip it through searchParams.
Passing a URL Inside a URL
OAuth redirect_uri values and "return to" parameters embed one full URL inside another. The inner URL's ?, &, and # must be encoded or they will be read as part of the outer URL. Setting it through searchParams does this for you, and reading it back returns the original:
const cb = new URL("https://app.example.com/auth/callback");
cb.searchParams.set("redirect_uri", "https://app.example.com/home?tab=1&x=2");
cb.href
// "https://app.example.com/auth/callback?redirect_uri=https%3A%2F%2Fapp.example.com%2Fhome%3Ftab%3D1%26x%3D2"
new URL(cb.href).searchParams.get("redirect_uri")
// "https://app.example.com/home?tab=1&x=2"Validating Redirect Targets
The open-redirect warning above has a concrete fix: parse the untrusted value against your own origin and compare origins, rather than inspecting the string. This handles absolute URLs, protocol-relative //host values, and backslash tricks that browsers treat as slashes:
function safeNext(next, origin = "https://app.example.com") {
try {
const t = new URL(next, origin);
return t.origin === origin ? t.pathname + t.search + t.hash : "/";
} catch {
return "/";
}
}
safeNext("/home?x=1") // "/home?x=1"
safeNext("https://app.example.com/ok") // "/ok"
safeNext("//evil.com") // "/"
safeNext("https://evil.com") // "/"
safeNext("/\\evil.com") // "/"
safeNext("javascript:alert(1)") // "/"Redirecting to a relative path built from the parsed result, instead of the raw input, means a parsing disagreement between your validator and the browser cannot send a user off-site. For an allowlist of several trusted hosts, compare t.origin against a set. See Understanding URL Redirects for how redirect chains behave, and check your own links with the URL Redirect Checker.
Checklist Before You Ship a URL Builder
- Encode every dynamic path segment and query value exactly once, in exactly one layer.
- Use
new URL(relative, base)orurl.searchParamsinstead of+and template strings for anything user-controlled. - Pick one array format and document it for API consumers.
- Normalize trailing slashes and parameter order wherever URLs are used as cache keys.
- Never put secrets in URLs: they can end up in logs, browser history, and
Refererheaders. - Validate redirect and callback targets by parsed origin, with an allowlist.
- Inspect the result with the URL Parser when debugging.
Trying It Without Code
The URL Builder lets you assemble a link from its parts (scheme, host, path, query parameters, fragment) and percent-encodes each query key and value as you type. It is handy for checking what a URL should look like before you write the code that produces it. It runs in your browser.
Frequently Asked Questions
How do I add query parameters to a URL in JavaScript?
Create a URL object and call url.searchParams.set(key, value) or append. The values are encoded automatically, and url.toString() returns the final string.
Should URLs end with a trailing slash?
Either convention works as long as you pick one and redirect the other to it, because servers may treat /page and /page/ as different resources. Remember that the trailing slash also changes how relative links on that page resolve.
How long can a URL be?
There is no limit in the URL syntax itself. Limits come from browsers, proxies, and servers, and they vary, so keep URLs short and move large payloads into a POST body. A server that rejects a long URL typically responds with 414 URI Too Long.
How do I safely redirect to a URL from a query parameter?
Parse the value against your own origin with new URL(value, origin) and only redirect when the resulting origin matches yours or an allowlisted one. Never check with startsWith on the raw string.
Written by Kashyap Thakar
Spotted a mistake? Let me know
Try these tools
Use these tools alongside this guide