Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท path, os and url

Node.js URL.parse() static method

Reference for the static URL.parse() in Node.js: parse a string into a URL object or get null on failure, how it differs from new URL() and legacy url.parse().

URL.parse(input, base) parses a string with the WHATWG URL algorithm and returns a URL object, or null when the string is not valid. It is the non-throwing twin of new URL(): same parser, same result for valid input, but no exception for bad input.

This is the method to reach for when invalid URLs are normal, for example when you scan user-provided text or a log file. You get the object and the validity check in one step. Do not confuse it with the deprecated legacy url.parse() function from the node:url module, which is a different parser; see url.parse() (legacy).

NODE
const url = URL.parse('https://example.com/a?x=1');
console.log(url?.searchParams.get('x')); // "1"
console.log(URL.parse('nope'));          // null

Try it

Node.js Parse or null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Filtering a list of links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
URL.parse(input[, base])
Name Description
input The string to parse. Non-strings are converted with String().
base Optional base URL string, used when input is relative.

Returns: a URL, or null if parsing fails (including an invalid base).

Errors: none for invalid URLs. The null result replaces the ERR_INVALID_URL TypeError thrown by new URL().

Usage notes

  • Pair it with optional chaining: URL.parse(value)?.hostname ?? 'unknown'.
  • null is falsy, so .filter(Boolean) removes failures from a list.
  • A valid result only means the syntax is correct. Check protocol before using the URL in a request, redirect or file operation.
  • Use URL.canParse() when you only need a boolean and will not keep the object.
  • The static method was added in Node.js 22.1. On older runtimes, fall back to a try/catch helper around new URL().
  • Unlike legacy url.parse(), it never guesses: example.com/path without a scheme is invalid, not a path.