On this page
JavaScript URL.canParse() lets you check whether a string can be parsed as a URL without using an exception for ordinary invalid input. It is useful for validating user-entered links, but a true result does not mean a destination is safe, trusted, or reachable.
This tutorial shows absolute and base-relative URLs, a fallback for environments without URL.canParse(), and a small form with useful error messages.
Key Takeaways
URL.canParse(input)returnstrueif the URL parser can parse the input as an absolute URL.URL.canParse(input, base)also accepts relative references that can be resolved against a valid base URL.- A parseable URL can still use an unwanted scheme or point to an unsafe or unreachable destination.
- Feature-detect
URL.canParse()and fall back tonew URL()insidetry...catchwhen it is unavailable.
What JavaScript URL.canParse() checks
URL.canParse() answers a syntax and parsing question: can the URL parser produce a URL from these arguments? It returns a boolean rather than the parsed URL.
URL.canParse('https://example.com/path'); // true
URL.canParse('not a URL'); // false
URL.canParse('example.com'); // false: no scheme or base
URL.canParse('mailto:hello@example.com'); // true
The last example is parseable, but it is not an HTTP or HTTPS link. If your application only accepts web links, check the parsed URL's protocol separately.
URL parsing is not the same as checking whether a website exists. For example, an address can parse successfully even if its hostname does not resolve. Parsing can also normalize input; it is not a guarantee that the original text follows your preferred formatting rules.
Advertisement
Parse relative URLs with a base
A relative reference needs a base URL. The parser resolves it against that base:
URL.canParse('../guide', 'https://example.com/docs/start/'); // true
const resolved = new URL('../guide', 'https://example.com/docs/start/');
console.log(resolved.href); // https://example.com/docs/guide
URL.canParse('../guide'); // false: no base
URL.canParse('../guide', 'not a valid base'); // false
The base matters: a trailing slash changes which path segment is treated as the starting directory. An invalid supplied base causes parsing to fail even when the input is an absolute URL:
URL.canParse('https://example.com/', 'not a valid base'); // false
When a base comes from a user or configuration, validate it independently so you can report which field needs attention. An optional blank base can be treated as absent; a nonblank invalid base should not silently be ignored.
Support environments without URL.canParse()
The examples below require a runtime with the URL constructor. If URL.canParse() is missing, the fallback uses that constructor and catches its invalid-URL error:
function canParseURL(input, base) {
if (typeof URL.canParse === 'function') {
return base === undefined
? URL.canParse(input)
: URL.canParse(input, base);
}
try {
if (base === undefined) {
new URL(input);
} else {
new URL(input, base);
}
return true;
} catch (error) {
if (error instanceof TypeError) return false;
throw error;
}
}
This helper is intended for string inputs. If your runtime also lacks the URL constructor, use an appropriate supported runtime or a compatible URL implementation instead.
The current MDN compatibility table could not be consulted in this environment, so this article does not claim a minimum browser or runtime version. Check MDN's URL.canParse() compatibility table for your target environments and use feature detection rather than assuming support. The examples have not been executed here; check them in your supported runtimes.
Build a form with helpful errors
Save the following as url-check.html and open it in a browser with the URL constructor. It accepts either an absolute HTTP(S) URL or a relative reference with an absolute base. The fallback handles browsers that have URL but lack URL.canParse().
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Check a URL</title>
</head>
<body>
<form id="url-form">
<label for="link">URL or relative path</label>
<input id="link" type="text" autocomplete="off">
<label for="base">Base URL, if needed</label>
<input id="base" type="text" autocomplete="off">
<button type="submit">Check URL</button>
</form>
<p id="result" role="status" aria-live="polite"></p>
<script>
function canParseURL(input, base) {
if (typeof URL.canParse === 'function') {
return base === undefined
? URL.canParse(input)
: URL.canParse(input, base);
}
try {
if (base === undefined) new URL(input);
else new URL(input, base);
return true;
} catch (error) {
if (error instanceof TypeError) return false;
throw error;
}
}
const form = document.getElementById('url-form');
const linkField = document.getElementById('link');
const baseField = document.getElementById('base');
const result = document.getElementById('result');
form.addEventListener('submit', (event) => {
event.preventDefault();
const input = linkField.value.trim();
const baseText = baseField.value.trim();
const base = baseText === '' ? undefined : baseText;
if (!input) {
result.textContent = 'Enter a URL or relative path.';
return;
}
if (base !== undefined && !canParseURL(base)) {
result.textContent = 'Enter a valid absolute base URL, including its scheme.';
return;
}
if (!canParseURL(input, base)) {
result.textContent = 'Enter a valid absolute URL, or provide a base for a relative path.';
return;
}
const parsed = base === undefined ? new URL(input) : new URL(input, base);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
result.textContent = 'Use an HTTP or HTTPS URL.';
return;
}
result.textContent = 'Parseable web URL: ' + parsed.href;
});
</script>
</body>
</html>
Try /about with base https://example.com/docs/; the displayed URL should be https://example.com/about. Try mailto:hello@example.com without a base to see the scheme-specific error. The message says “parseable,” not “safe” or “reachable.”
The form trims surrounding whitespace as an application choice. It writes the result with textContent, rather than inserting user input as HTML. Server-side validation is still necessary if the URL is submitted to a server.
Advertisement
Syntax is not a security or availability check
A parseable HTTP(S) URL may point to an attacker-controlled site, a private network address, or a service that does not respond. Protocol filtering is useful policy enforcement, but it is not a complete security check.
If a server will fetch a user-provided URL, apply server-side controls appropriate to the service. These typically include restricting schemes and destinations; checking resolved IPv4 and IPv6 addresses for loopback, private, link-local, and other prohibited ranges; and ensuring the connection uses a vetted address so DNS changes cannot bypass the check. Revalidate every redirect, restrict network egress, set timeouts and response-size limits, and require authentication and authorization where appropriate. A hostname check or URL parser alone does not prevent server-side request forgery.
If you need to check reachability, that is a separate network operation with its own timeout, privacy, and security considerations. A failed request may also reflect network policy or a temporary outage rather than invalid syntax.
Common Mistakes
- Assuming a domain-like string is absolute.
example.comhas no scheme and fails without a base. Ask for a complete URL or explicitly define how your application adds a scheme. - Passing an invalid base and blaming the link. Validate a provided base separately, including when the link itself is absolute.
- Treating
trueas approval. Check the parsed protocol and enforce any destination policy separately. - Assuming relative paths resolve from the domain root. A leading slash resolves from the root; other relative paths depend on the base path and its trailing slash.
- Relying only on browser-side validation. Repeat relevant checks on the server, where requests can be made without your form.
Best Practices
Use URL.canParse() when you need a boolean and already have string input. When you need the parsed components anyway, new URL() inside try...catch can both validate and produce the object in one step. Keep syntax errors, unsupported schemes, and network failures as distinct messages so users know what to fix.
Conclusion
URL.canParse() is a convenient way to check whether JavaScript can parse a URL, including a relative reference with a valid base. Combine it with feature detection, application-specific scheme rules, and server-side security controls; do not mistake parsing for trust or reachability.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.