Skip to main content
Back to Blog

URL Validation: Why Regular Expressions Aren't Enough

Why regex alone isn’t enough for URLs and how to validate scheme, host, and encoding before using a link.

Kashyap Thakar
9 min
SecurityValidationURLRegex
URL Validation: Why Regular Expressions Aren't Enough

"Is this a valid URL?" It's a question every form validation script has to answer. But what exactly counts as a valid URL? Is localhost valid? What about http://10.0.0.1? Or international domains such as münchen.de? The answer depends entirely on your context, and getting it wrong can lead to UX nightmares or security holes.

The Pitfalls of Simple Regex

You've probably seen (or written) a regex like this:

^http(s)?:\/\/([a-z0-9-]+\.)+[a-z]...

While this catches the most common web addresses, it rejects inputs that real users legitimately type. It likely rejects:

  • Local references: http://localhost:3000
  • IP addresses: http://192.168.1.1
  • International domains: http://münchen.de (not valid in the RFC 3986 grammar, but browsers accept it and convert the host to Punycode)
  • Protocol-relative references: //example.com (only valid with a base URL)

The ReDoS Threat

Beyond correctness, complex regular expressions are vulnerable to ReDoS (Regular Expression Denial of Service). A specially crafted, long "almost valid" string can make a backtracking regex engine take far longer than expected, blocking the browser's main thread or your Node.js event loop. Whether a given pattern is vulnerable depends on its structure, which is another reason to avoid long hand-written URL patterns.

Security Implications: SSRF

Poor validation isn't just a formatting issue. It's a security vulnerability. Server-Side Request Forgery (SSRF) attacks exploit weak validation to trick servers into accessing internal resources.

If your validator allows http://localhost/admin or http://169.254.169.254 (AWS metadata), an attacker could scrape confidential internal data by submitting these as "valid" profile links.

How to Validate Correctly

Don't reinvent the wheel. Use the native URL constructor, available in browsers and Node.js. It implements the WHATWG URL Standard, so it parses the same way browsers do.

function isValid(string) {
  try {
    new URL(string);
    return true;
  } catch (_) {
    return false;
  }
}

What the parser actually does

The URL constructor follows the WHATWG URL Standard, which is what browsers implement. It parses, normalizes and throws a TypeError on failure. These results come from running the following inputs in Node.js:

InputResult
example.comThrows (no scheme)
//example.comThrows without a base URL
http://münchen.dehttp://xn--mnchen-3ya.de/
HTTP://EXAMPLE.com:80/a/../bhttp://example.com/b
http://2130706433http://127.0.0.1/
http://0x7f.1http://127.0.0.1/
http://exa mple.comThrows
javascript:alert(1)Parses successfully, protocol javascript:

Three lessons here. First, //example.com is a relative reference, so it needs a base: new URL("//example.com/x", "https://site.test") resolves to https://example.com/x. Second, parsing normalizes the host, so decimal and hexadecimal IP tricks collapse to a plain dotted address that your checks can see. Always inspect the parsed hostname, never the raw string. Third, a successful parse says nothing about safety: javascript:alert(1) and data: URLs are perfectly well-formed.

In current runtimes you can also use the non-throwing URL.canParse(), which returned true for https://example.com and false for nope. Beware of strings that look like host names but are not: new URL("localhost:3000") parses successfully, with the scheme localhost: and the path 3000, so a bare host:port is not rejected the way example.com is. Parsing is also more lenient than DNS: https://exa_mple.com and https://-bad-.com both parse. The URL Standard does not enforce every hostname rule, so "parses" is not the same as "is a registrable domain".

A Safe Allow-List Validator

For user-supplied links that will be rendered in an href or stored, parse, check the scheme against an allow-list, and keep the normalized output rather than the raw input:

function safeHttpUrl(input) {
  if (typeof input !== "string" || input.length > 2048) return null;
  let u;
  try { u = new URL(input.trim()); } catch { return null; }
  return u.protocol === "http:" || u.protocol === "https:" ? u : null;
}

safeHttpUrl("https://example.com/x")?.href  // "https://example.com/x"
safeHttpUrl("javascript:alert(1)")          // null
safeHttpUrl("data:text/html,hi")            // null
safeHttpUrl("ftp://x.com")                  // null

An allow-list beats a deny-list because new or obscure schemes never slip through by default. The 2048 limit here is an application choice, not a standard. There is no single maximum URL length in RFC 3986. RFC 9110 recommends that HTTP software support at least 8,000 octets, while individual servers, proxies and CDNs enforce their own, often smaller, limits. Pick a limit that suits your use case and enforce it before parsing to bound the work done on hostile input.

Server-Side Fetching and SSRF in Practice

When your server fetches a user-supplied URL (link previews, webhooks, image imports), the URL is an instruction for your network. A first-line check on the parsed URL looks like this:

import { isIPv4 } from "node:net";

function isPrivateIPv4(h) {
  if (!isIPv4(h)) return false;
  const [a, b] = h.split(".").map(Number);
  return a === 10 || a === 127 || a === 0 ||
    (a === 172 && b >= 16 && b <= 31) ||
    (a === 192 && b === 168) ||
    (a === 169 && b === 254);
}

function checkTarget(input) {
  const u = new URL(input);
  if (!["http:", "https:"].includes(u.protocol)) return "blocked: scheme";
  if (u.hostname === "localhost" || u.hostname.startsWith("[")) return "blocked: host";
  if (isPrivateIPv4(u.hostname)) return "blocked: private IP";
  return "ok";
}

Running it gives ok for https://example.com, and blocks http://169.254.169.254/latest/meta-data, http://2130706433/, http://0x7f.1/ and http://172.20.1.1 as private IPs, http://localhost:3000 and http://[::1]/ as hosts, and ftp://example.com by scheme. Note how the decimal and hex forms are caught only because the parser normalized them first.

This is a sketch, not a complete defense. A string check on the hostname cannot see where a name resolves, so a real implementation also needs to handle:

  • DNS resolution: a public-looking hostname can point to a private address. Resolve the name yourself, reject private, loopback and link-local results (IPv4 and IPv6, including IPv4-mapped IPv6 forms), and connect to the address you checked.
  • DNS rebinding: if you validate one lookup and your HTTP client performs a second, an attacker-controlled DNS server can return a different answer the second time. Pinning the connection to the validated IP closes this gap.
  • Redirects: a harmless URL can answer with a redirect to an internal one. Disable automatic redirects or re-validate every hop, and cap the hop count.
  • Resource limits: set timeouts and maximum response sizes, and restrict ports where you can.
  • Network-level controls: run fetchers in a segment that cannot reach internal services at all. Application checks are a second layer, not the only one.

Redirect Targets and Open Redirects

For "return to" parameters, prefer relative paths and verify them by origin rather than by prefix. A string that starts with / is not automatically safe, because //evil.test/path is a protocol-relative URL. Resolving against your own origin exposes the difference:

const base = "https://app.test";
new URL("//evil.test/path", base).origin === base  // false
new URL("/dashboard", base).origin === base        // true

If the resolved origin is not yours (or on a short allow-list), refuse the redirect. See HTTP Redirects: 301 vs 302 and Debugging Chains for how redirect chains behave once a request is in flight.

Normalization and Duplicates

Two strings can point to the same resource. Parsing https://EXAMPLE.com:443/a/./b/../c?b=2&a=1#top yields https://example.com/a/c?b=2&a=1#top: the host is lowercased, the default port is dropped and dot segments are resolved. Query parameter order is preserved, so ?a=1&b=2 and ?b=2&a=1 remain distinct strings even if your server treats them identically. Decide your own canonical form (for example, strip fragments and tracking parameters, sort query keys) before using URLs as database keys or for de-duplication. Percent-encoding is normalized too: https://example.com/a b?q=ü#f becomes https://example.com/a%20b?q=%C3%BC#f. For more, see URL Encoding & Decoding: Definitive Guide and URL Anatomy: Parsing and Building Robust Links.

Valid Versus Reachable

There are three separate questions, and they need three separate checks:

  • Well-formed: does it parse? Use the URL parser.
  • Acceptable: is the scheme, host and length allowed by your policy? Use an allow-list.
  • Reachable: does the server answer, and with what status? Only a network request can tell, and the answer can change tomorrow. Treat it as a separate, asynchronous, rate-limited job. The URL redirect checker is useful when you want to see where a link really ends up.

Also remember that credentials can hide in the authority part: https://user:[email protected]/ parses with the hostname example.com, and https://[email protected] has the hostname evil.com. If you display URLs to users, show the parsed hostname rather than the raw string, and consider rejecting URLs containing credentials.

Why Not Just Fix the Regex?

RFC 3986 grammar plus the WHATWG parsing rules (which browsers follow, and which differ from the RFC in places) are too intricate for a maintainable regex, and any regex you write will disagree with the parser your browser or HTTP client uses. That disagreement is where security bugs live: the validator approves a string and the fetcher interprets it differently. Using the same parser for validation and for use removes that class of problem. Regex still has a role for narrow, well-bounded checks, such as matching a known hostname suffix on the already-parsed hostname. For help with that, see the regex cheat sheet.

Validation Strategies by Use Case

User Input (Forms)

For user-submitted URLs (profile links, website fields):

  • Validate format using native URL constructor
  • Restrict to http/https protocols only
  • Allow localhost only in development builds, never in production
  • Provide clear error messages for invalid formats

Server-Side Fetching

When your server will fetch the URL:

  • Validate the format, then apply the SSRF checks described above (private and loopback addresses, DNS resolution, redirects)
  • Use an allow-list of domains if the feature permits it
  • Rate-limit the endpoint to prevent abuse

Redirect URLs

For "return to" or redirect parameters:

  • Validate format strictly
  • Compare the parsed origin against an allow-list (prevents open redirects)
  • Reject javascript:, file:, and data: protocols
  • Consider using relative URLs instead

Testing Your Validator

Test your URL validator with these edge cases:

  • http://localhost:3000 (should allow for dev, block for production)
  • https://example.com/path?query=value#fragment (complete URL)
  • //example.com (protocol-relative)
  • http://192.168.1.1 (private IP - block if server-side)
  • javascript:alert('xss') (should always reject)
  • http://münchen.de (international domain)
  • http://example.com:8080 (non-standard port)

Cleaning Up a Large Set of URLs

Auditing thousands of imported links is a scripting job, not a clicking job. The URL constructor is the right primitive: it either parses or throws, so a few lines separate the salvageable rows from the broken ones without any regex.

Run that pass first and the failures often fall into a few fixable shapes, such as a missing scheme, a stray space from a spreadsheet paste, smart quotes, or trailing punctuation picked up from prose. Repair those patterns in bulk, then re-run. What still fails after that is genuinely malformed and worth inspecting individually.

Keep syntactic validation and reachability separate. A URL can parse perfectly and still 404, and a HEAD request against every row is slow, rate-limited, and prone to false negatives from bot protection. Validate structure offline, then check liveness only for the subset that matters.

For a single link you want to check by hand, our URL validator gives a quick answer, but it is a sanity check rather than a policy engine. Its format check is a regular expression, so it has the limits described at the top of this article (for example, it rejects localhost and non-ASCII host names), and its reachability check is a no-cors request made from your browser. Use the URL Parser to see how the standard parser splits a link.

Frequently Asked Questions

What is the best way to validate a URL in JavaScript?

Parse it with new URL() (or URL.canParse()), then check protocol against an allow-list of http: and https:. Use the parsed object, not the raw string, for everything afterwards.

Is new URL() enough to make a URL safe?

No. It only confirms the string is well-formed. javascript:, data: and URLs pointing at internal addresses all parse successfully, so you still need scheme and host checks.

How do I prevent SSRF when fetching user-supplied URLs?

Allow only http and https, resolve the hostname and reject private, loopback and link-local addresses, connect to the validated IP, and re-check every redirect. Combine this with network-level isolation, timeouts and response size limits.

Does a valid URL mean the website exists?

No. Validity is about syntax. Whether the host resolves and returns a successful response can only be learned with a network request, and it can change over time.

Why does new URL("example.com") throw an error?

Without a scheme, the parser cannot tell it is an absolute URL. Either require users to include https://, or prepend it yourself and re-validate the result.

Written by

Spotted a mistake? Let me know