On this page
A user-submitted URL is not automatically safe to put in an HTML link. A value such as javascript:alert(1) can turn a click into script execution. To safely render user submitted URLs as links, parse each candidate, allow only intended schemes, and use the correct HTML output handling.
This guide treats an entire submitted field as one URL candidate. If you linkify URLs inside comments or chat messages, first identify candidate spans and apply the same checks to each one; render the surrounding text as text, not HTML.
Key Takeaways
- Require an explicit
http://orhttps://prefix, parse the candidate, and check the parsed protocol against an allowlist. - URL parsing and HTML escaping solve different problems. Use both when generating HTML strings; use DOM APIs to avoid building those strings in the browser.
- Render rejected candidates as plain text. Do not silently prepend a scheme unless that behavior is an explicit product decision.
- Allowing HTTP and HTTPS does not establish that a destination is trustworthy or protect a server that fetches it.
Define the link policy first
The examples below use a deliberately narrow policy:
- Trim whitespace at the beginning and end of the submission, but reject whitespace or control characters within the remaining candidate.
- Require an explicit
http://orhttps://prefix, ignoring scheme case. - Parse the candidate as an absolute URL without a base URL.
- Allow only parsed
http:andhttps:protocols, require a hostname, and reject embedded usernames or passwords. - Display accepted links using the parsed URL's serialized form. Display rejected submissions as plain text.
This policy rejects some URLs that could otherwise be represented with encoded characters. That is intentional: a predictable, narrow rule is easier to explain than silently repairing ambiguous input. Rejecting embedded credentials also avoids links whose apparent destination can be misleading.
Advertisement
Safely render user submitted URLs as links in the browser
The following JavaScript is for a browser environment with the standard URL and DOM APIs. normalizeCandidate returns a serialized URL or null; createSafeLink returns either an anchor or a text node. The submitted value must be a string.
function normalizeCandidate(input) {
const candidate = input.trim();
// This policy requires a visible, explicit HTTP(S) prefix.
if (!/^https?:\/\//i.test(candidate)) return null;
// Reject internal whitespace and control characters rather than repair them.
if (/[\s\u0000-\u001f\u007f]/u.test(candidate)) return null;
try {
// No base URL: relative paths must not become links to the current site.
const url = new URL(candidate);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
if (!url.hostname || url.username || url.password) return null;
return url.href;
} catch {
return null;
}
}
function createSafeLink(input) {
const href = normalizeCandidate(input);
if (href === null) return document.createTextNode(input);
const anchor = document.createElement("a");
anchor.href = href;
anchor.textContent = href;
return anchor;
}
// Example: render one submitted URL field into an existing container.
const container = document.querySelector("#submitted-url");
if (container) {
container.replaceChildren(createSafeLink("https://example.com/?a=1&b=2"));
}
Add an element such as <div id="submitted-url"></div> to the page before running the script. When rendering a comment, append text nodes for non-link portions and nodes from createSafeLink for candidate portions; do not assign the combined user content to innerHTML.
Setting textContent inserts text rather than interpreting it as markup. Assigning the already validated URL through the DOM's href property avoids manually constructing a quoted HTML attribute. Neither DOM API makes an unsafe scheme safe on its own: the protocol check is still necessary.
If you generate HTML strings, escape for each context
A server-side template may need to produce HTML rather than DOM nodes. In that case, parse and validate the original candidate first, then HTML-escape both the quoted attribute value and the visible text. Do not escape before parsing and then assume the result is a validated URL.
This illustrative JavaScript uses normalizeCandidate from the preceding example. It returns an HTML fragment, so insert that fragment only where HTML is expected.
function escapeHtml(value) {
return value.replace(/[&<>"']/g, (character) => {
switch (character) {
case "&": return "&";
case "<": return "<";
case ">": return ">";
case '"': return """;
case "'": return "'";
}
});
}
function renderUrlHtml(input) {
const href = normalizeCandidate(input);
if (href === null) return escapeHtml(input);
const escapedHref = escapeHtml(href);
const escapedLabel = escapeHtml(href);
return `<a href="${escapedHref}">${escapedLabel}</a>`;
}
The attribute is always double-quoted, and the escaping function encodes characters relevant to that HTML context. In particular, an ampersand in a query string must be escaped in the HTML source. A template engine with automatic context-aware escaping can do this instead, but do not mark untrusted input as already-safe HTML. URL percent-encoding is not a substitute for HTML attribute escaping, and HTML escaping does not make a dangerous URL scheme acceptable.
Advertisement
Check edge cases against your policy
The following are cases to verify in your own environment. These examples describe the intended behavior of the code above; they are not execution results.
| Submitted candidate | Intended treatment | Reason |
|---|---|---|
javascript:alert(1) | Plain text | Not an allowed HTTP(S) URL. |
data:text/html,hello | Plain text | data: is not allowed. |
JaVaScRiPt:alert(1) | Plain text | Changing scheme case does not make it allowed. |
HTTPS://example.com/path | Link | The prefix check ignores case; the parsed protocol must still be allowed. |
https://example.com/ | Link | Surrounding whitespace is trimmed. |
https://example.com/a b | Plain text | Internal whitespace is rejected by this policy. |
https://[ | Plain text | Parsing fails for the malformed host. |
example.com/path | Plain text | There is no explicit scheme. |
/relative/path | Plain text | Relative URLs are not accepted. |
https://user:pass@example.com/ | Plain text | Embedded credentials are rejected. |
Also check quotes, angle brackets, ampersands, and Unicode hostnames in both accepted and rejected inputs. Confirm that rejected text is displayed literally and that accepted links navigate to the parsed destination. Browser URL parsing can normalize the displayed URL; review whether that presentation fits your product.
The TidyURLs URL Parser can help inspect URL components, but it is not a security validator or sanitizer. Your application must enforce its own policy and output handling.
Common Mistakes
- Checking only for a colon or a valid parse. A parser can recognize schemes your application must not allow.
- Checking only the original string. Validate the parsed protocol and hostname as well as any prefix rule; parser normalization can affect interpretation.
- Putting raw input into
innerHTML. Even a rejected URL must be rendered as text or escaped for its output context. - Assuming escaped text means a safe destination. HTML escaping protects the markup context; it does not block phishing, tracking, or other harmful HTTP(S) destinations.
- Reusing this policy for redirects or server-side fetching. Those operations need separate authorization and destination controls; an HTTP(S) allowlist alone is not an SSRF defense.
Best Practices
Apply the same policy wherever user-provided links are rendered, including previews and moderation views. Keep candidate extraction separate from validation, and test the full rendering path rather than only the URL parser. Consider content moderation and visible destination indicators for phishing risks; a syntactically valid HTTPS URL can still lead to an untrustworthy site.
If links must open in a new tab, set rel="noopener noreferrer" along with target="_blank". Use a Content Security Policy as defense in depth, not as a replacement for validation and safe output handling.
The WHATWG URL Standard and OWASP Cross Site Scripting Prevention Cheat Sheet were not available for consultation for this draft. Verify the parsing and output-encoding behavior against those sources and test the examples in your supported environments before deployment; the examples have not been executed here.
Conclusion
Treat a user-supplied link as both a URL-policy decision and an output-encoding problem. Parse and allow only the schemes your application supports, then render the result with DOM APIs or context-correct HTML escaping.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.