Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readJavaScriptWeb Platform

Validate a URL with URL.canParse

Use URL.canParse to check whether a string parses and apply a separate protocol check for HTTP links.

You need to know whether a string is a URL before you store it. You can try the URL constructor and catch a parse error.

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

This works for string inputs and allocates a URL object you immediately discard.

One call

URL.canParse() uses the constructor’s parser. For string inputs it returns false on parse failure.

URL.canParse('https://example.com/path') // true
URL.canParse('example.com') // false
URL.canParse('/docs') // false
URL.canParse('/docs', 'https://example.com') // true

The second argument is the base, as in the constructor. A relative path on its own is not a URL, so it returns false; with a base it resolves and returns true. The function above becomes const isValidUrl = (input) => URL.canParse(input), or you drop it and call canParse at the site.

Browser support reached Baseline in December 2023. Node added it in 18.17.0 and 19.9.0. For older targets, keep the constructor fallback.

Update, November 2026. URL.parse reached Baseline in September 2024 and arrived in Node 22.1.0. It returns a URL object or null, which saves a second parse when you need the object.

Check the protocol

URL.canParse('mailto:hi@example.com') is true. So is javascript:alert(1).

The method answers one question, whether the string parses as a URL, and mailto: and javascript: are valid schemes. A form field that should hold a link needs a second check on the protocol.

function isHttpUrl(input) {
  if (!URL.canParse(input)) return false
  const { protocol } = new URL(input)
  return protocol === 'http:' || protocol === 'https:'
}

isHttpUrl('https://example.com') is true, and both mailto:hi@example.com and not a url are false. On older targets, a single new URL(input) inside try/catch can both parse the string and give you the protocol.