← All posts

TIL: URL.canParse() — Validate URLs Without try/catch

URL.canParse() returns true or false for a URL string — no more wrapping new URL() in a try/catch just to check if the input is valid.

Michael Cooper2 min readYellow belt

TIL about URL.canParse() — a static method that tells you whether a string is a valid URL without throwing an exception. It has been in every major runtime since mid-2023.

The old way: try/catch

Validating a URL used to look like this:

js
function isValidUrl(input) {
  try {
    new URL(input);
    return true;
  } catch {
    return false;
  }
}

Using exceptions for control flow is a code smell, and it is noticeably slower than a simple boolean check in tight loops.

URL.canParse()

js
URL.canParse('https://example.com/path?q=1'); // true
URL.canParse('not a url');                    // false
URL.canParse('');                             // false

It takes the same two arguments as new URL(): a URL string and an optional base URL.

js
// Relative URL against a base — same signature as new URL()
URL.canParse('/about', 'https://mysite.com');  // true
URL.canParse('../oops', 'not-a-base');         // false

This makes it a natural guard before constructing the URL object:

js
function parseUrlSafely(input, base) {
  if (!URL.canParse(input, base)) return null;
  return new URL(input, base);
}

Practical uses

Form validation:

js
function validateLink(value) {
  if (!URL.canParse(value)) {
    return 'Please enter a valid URL including https://';
  }
  const url = new URL(value);
  if (url.protocol !== 'https:') {
    return 'Only HTTPS links are allowed';
  }
  return null;
}

Sanitizing user-submitted links before storing:

js
const safeLinks = rawLinks.filter(href => URL.canParse(href));

Filtering an array of mixed strings — no silent exception swallowing:

js
const urls = inputs
  .filter(s => URL.canParse(s))
  .map(s => new URL(s));

Support

| Environment | Since | |-------------|-------| | Node.js | 18.17 / 19.9 | | Chrome | 120 | | Firefox | 115 | | Safari | 17 |

Baseline availability since late 2023, so it is safe in any modern environment. For anything older, isValidUrl with try/catch above still works fine as a polyfill.

Why it matters

It is a small addition, but it matters for readability. URL.canParse(str) reads as a plain predicate — exactly what a guard clause should be. The try/catch version hides what the code is actually doing behind exception handling mechanics. Reach for URL.canParse any time you need to check a URL before using it rather than parse it unconditionally.