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).
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
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.
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
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'. nullis falsy, so.filter(Boolean)removes failures from a list.- A valid result only means the syntax is correct. Check
protocolbefore 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/catchhelper aroundnew URL(). - Unlike legacy
url.parse(), it never guesses:example.com/pathwithout a scheme is invalid, not a path.