URL#

Stability: 2 - Stable

Source Code:lib/url.js

Thenode:url module provides utilities for URL resolution and parsing. It canbe accessed using:

import urlfrom'node:url';const url =require('node:url');

URL strings and URL objects#

A URL string is a structured string containing multiple meaningful components.When parsed, a URL object is returned containing properties for each of thesecomponents.

Thenode:url module provides two APIs for working with URLs: a legacy API thatis Node.js specific, and a newer API that implements the sameWHATWG URL Standard used by web browsers.

A comparison between the WHATWG and legacy APIs is provided below. Above the URL'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', propertiesof an object returned by the legacyurl.parse() are shown. Below it areproperties of a WHATWGURL object.

WHATWG URL'sorigin property includesprotocol andhost, but notusername orpassword.

┌────────────────────────────────────────────────────────────────────────────────────────────────┐│                                              href                                              │├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤│ protocol │  │        auth         │          host          │           path            │ hash  ││          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       ││          │  │                     │    hostname     │ port │ pathname │     search     │       ││          │  │                     │                 │      │          ├─┬──────────────┤       ││          │  │                     │                 │      │          │ │    query     │       │"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "│          │  │          │          │    hostname     │ port │          │                │       ││          │  │          │          ├─────────────────┴──────┤          │                │       ││ protocol │  │ username │ password │          host          │          │                │       │├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       ││   origin    │                     │         origin         │ pathname │     search     │ hash  │├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤│                                              href                                              │└────────────────────────────────────────────────────────────────────────────────────────────────┘(All spaces in the "" line should be ignored. They are purely for formatting.)

Parsing the URL string using the WHATWG API:

const myURL =newURL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');

Parsing the URL string using the legacy API:

import urlfrom'node:url';const myURL =  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');const url =require('node:url');const myURL =  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');

Constructing a URL from component parts and getting the constructed string#

It is possible to construct a WHATWG URL from component parts using either theproperty setters or a template literal string:

const myURL =newURL('https://example.org');myURL.pathname ='/a/b/c';myURL.search ='?d=e';myURL.hash ='#fgh';
const pathname ='/a/b/c';const search ='?d=e';const hash ='#fgh';const myURL =newURL(`https://example.org${pathname}${search}${hash}`);

To get the constructed URL string, use thehref property accessor:

console.log(myURL.href);

The WHATWG URL API#

Class:URL#

History
VersionChanges
v10.0.0

The class is now available on the global object.

v7.0.0, v6.13.0

Added in: v7.0.0, v6.13.0

Browser-compatibleURL class, implemented by following the WHATWG URLStandard.Examples of parsed URLs may be found in the Standard itself.TheURL class is also available on the global object.

In accordance with browser conventions, all properties ofURL objectsare implemented as getters and setters on the class prototype, rather than asdata properties on the object itself. Thus, unlikelegacyurlObjects,using thedelete keyword on any properties ofURL objects (e.g.delete myURL.protocol,delete myURL.pathname, etc) has no effect but will stillreturntrue.

new URL(input[, base])#
History
VersionChanges
v20.0.0, v18.17.0

ICU requirement is removed.

  • input<string> The absolute or relative input URL to parse. Ifinputis relative, thenbase is required. Ifinput is absolute, thebaseis ignored. Ifinput is not a string, it isconverted to a string first.
  • base<string> The base URL to resolve against if theinput is notabsolute. Ifbase is not a string, it isconverted to a string first.

Creates a newURL object by parsing theinput relative to thebase. Ifbase is passed as a string, it will be parsed equivalent tonew URL(base).

const myURL =newURL('/foo','https://example.org/');// https://example.org/foo

The URL constructor is accessible as a property on the global object.It can also be imported from the built-in url module:

import {URL }from'node:url';console.log(URL === globalThis.URL);// Prints 'true'.console.log(URL ===require('node:url').URL);// Prints 'true'.

ATypeError will be thrown if theinput orbase are not valid URLs. Notethat an effort will be made to coerce the given values into strings. Forinstance:

const myURL =newURL({toString:() =>'https://example.org/' });// https://example.org/

Unicode characters appearing within the host name ofinput will beautomatically converted to ASCII using thePunycode algorithm.

const myURL =newURL('https://測試');// https://xn--g6w251d/

In cases where it is not known in advance ifinput is an absolute URLand abase is provided, it is advised to validate that theorigin oftheURL object is what is expected.

let myURL =newURL('http://Example.com/','https://example.org/');// http://example.com/myURL =newURL('https://Example.com/','https://example.org/');// https://example.com/myURL =newURL('foo://Example.com/','https://example.org/');// foo://Example.com/myURL =newURL('http:Example.com/','https://example.org/');// http://example.com/myURL =newURL('https:Example.com/','https://example.org/');// https://example.org/Example.com/myURL =newURL('foo:Example.com/','https://example.org/');// foo:Example.com/
url.hash#

Gets and sets the fragment portion of the URL.

const myURL =newURL('https://example.org/foo#bar');console.log(myURL.hash);// Prints #barmyURL.hash ='baz';console.log(myURL.href);// Prints https://example.org/foo#baz

Invalid URL characters included in the value assigned to thehash propertyarepercent-encoded. The selection of which characters topercent-encode may vary somewhat from what theurl.parse() andurl.format() methods would produce.

url.host#

Gets and sets the host portion of the URL.

const myURL =newURL('https://example.org:81/foo');console.log(myURL.host);// Prints example.org:81myURL.host ='example.com:82';console.log(myURL.href);// Prints https://example.com:82/foo

Invalid host values assigned to thehost property are ignored.

url.hostname#

Gets and sets the host name portion of the URL. The key difference betweenurl.host andurl.hostname is thaturl.hostname doesnot include theport.

const myURL =newURL('https://example.org:81/foo');console.log(myURL.hostname);// Prints example.org// Setting the hostname does not change the portmyURL.hostname ='example.com';console.log(myURL.href);// Prints https://example.com:81/foo// Use myURL.host to change the hostname and portmyURL.host ='example.org:82';console.log(myURL.href);// Prints https://example.org:82/foo

Invalid host name values assigned to thehostname property are ignored.

url.href#

Gets and sets the serialized URL.

const myURL =newURL('https://example.org/foo');console.log(myURL.href);// Prints https://example.org/foomyURL.href ='https://example.com/bar';console.log(myURL.href);// Prints https://example.com/bar

Getting the value of thehref property is equivalent to callingurl.toString().

Setting the value of this property to a new value is equivalent to creating anewURL object usingnew URL(value). Each of theURLobject's properties will be modified.

If the value assigned to thehref property is not a valid URL, aTypeErrorwill be thrown.

url.origin#
History
VersionChanges
v15.0.0

The scheme "gopher" is no longer special andurl.origin now returns'null' for it.

Gets the read-only serialization of the URL's origin.

const myURL =newURL('https://example.org/foo/bar?baz');console.log(myURL.origin);// Prints https://example.org
const idnURL =newURL('https://測試');console.log(idnURL.origin);// Prints https://xn--g6w251dconsole.log(idnURL.hostname);// Prints xn--g6w251d
url.password#

Gets and sets the password portion of the URL.

const myURL =newURL('https://abc:xyz@example.com');console.log(myURL.password);// Prints xyzmyURL.password ='123';console.log(myURL.href);// Prints https://abc:123@example.com/

Invalid URL characters included in the value assigned to thepassword propertyarepercent-encoded. The selection of which characters topercent-encode may vary somewhat from what theurl.parse() andurl.format() methods would produce.

url.pathname#

Gets and sets the path portion of the URL.

const myURL =newURL('https://example.org/abc/xyz?123');console.log(myURL.pathname);// Prints /abc/xyzmyURL.pathname ='/abcdef';console.log(myURL.href);// Prints https://example.org/abcdef?123

Invalid URL characters included in the value assigned to thepathnameproperty arepercent-encoded. The selection of which charactersto percent-encode may vary somewhat from what theurl.parse() andurl.format() methods would produce.

url.port#
History
VersionChanges
v15.0.0

The scheme "gopher" is no longer special.

Gets and sets the port portion of the URL.

The port value may be a number or a string containing a number in the range0 to65535 (inclusive). Setting the value to the default port of theURL objects givenprotocol will result in theport value becomingthe empty string ('').

The port value can be an empty string in which case the port depends onthe protocol/scheme:

protocolport
"ftp"21
"file"
"http"80
"https"443
"ws"80
"wss"443

Upon assigning a value to the port, the value will first be converted to astring using.toString().

If that string is invalid but it begins with a number, the leading number isassigned toport.If the number lies outside the range denoted above, it is ignored.

const myURL =newURL('https://example.org:8888');console.log(myURL.port);// Prints 8888// Default ports are automatically transformed to the empty string// (HTTPS protocol's default port is 443)myURL.port ='443';console.log(myURL.port);// Prints the empty stringconsole.log(myURL.href);// Prints https://example.org/myURL.port =1234;console.log(myURL.port);// Prints 1234console.log(myURL.href);// Prints https://example.org:1234/// Completely invalid port strings are ignoredmyURL.port ='abcd';console.log(myURL.port);// Prints 1234// Leading numbers are treated as a port numbermyURL.port ='5678abcd';console.log(myURL.port);// Prints 5678// Non-integers are truncatedmyURL.port =1234.5678;console.log(myURL.port);// Prints 1234// Out-of-range numbers which are not represented in scientific notation// will be ignored.myURL.port =1e10;// 10000000000, will be range-checked as described belowconsole.log(myURL.port);// Prints 1234

Numbers which contain a decimal point,such as floating-point numbers or numbers in scientific notation,are not an exception to this rule.Leading numbers up to the decimal point will be set as the URL's port,assuming they are valid:

myURL.port =4.567e21;console.log(myURL.port);// Prints 4 (because it is the leading number in the string '4.567e21')
url.protocol#

Gets and sets the protocol portion of the URL.

const myURL =newURL('https://example.org');console.log(myURL.protocol);// Prints https:myURL.protocol ='ftp';console.log(myURL.href);// Prints ftp://example.org/

Invalid URL protocol values assigned to theprotocol property are ignored.

Special schemes#
History
VersionChanges
v15.0.0

The scheme "gopher" is no longer special.

TheWHATWG URL Standard considers a handful of URL protocol schemes to bespecial in terms of how they are parsed and serialized. When a URL isparsed using one of these special protocols, theurl.protocol propertymay be changed to another special protocol but cannot be changed to anon-special protocol, and vice versa.

For instance, changing fromhttp tohttps works:

const u =newURL('http://example.org');u.protocol ='https';console.log(u.href);// https://example.org/

However, changing fromhttp to a hypotheticalfish protocol does notbecause the new protocol is not special.

const u =newURL('http://example.org');u.protocol ='fish';console.log(u.href);// http://example.org/

Likewise, changing from a non-special protocol to a special protocol is alsonot permitted:

const u =newURL('fish://example.org');u.protocol ='http';console.log(u.href);// fish://example.org

According to the WHATWG URL Standard, special protocol schemes areftp,file,http,https,ws, andwss.

url.search#

Gets and sets the serialized query portion of the URL.

const myURL =newURL('https://example.org/abc?123');console.log(myURL.search);// Prints ?123myURL.search ='abc=xyz';console.log(myURL.href);// Prints https://example.org/abc?abc=xyz

Any invalid URL characters appearing in the value assigned thesearchproperty will bepercent-encoded. The selection of whichcharacters to percent-encode may vary somewhat from what theurl.parse()andurl.format() methods would produce.

url.searchParams#

Gets theURLSearchParams object representing the query parameters of theURL. This property is read-only but theURLSearchParams object it providescan be used to mutate the URL instance; to replace the entirety of queryparameters of the URL, use theurl.search setter. SeeURLSearchParams documentation for details.

Use care when using.searchParams to modify theURL because,per the WHATWG specification, theURLSearchParams object usesdifferent rules to determine which characters to percent-encode. Forinstance, theURL object will not percent encode the ASCII tilde (~)character, whileURLSearchParams will always encode it:

const myURL =newURL('https://example.org/abc?foo=~bar');console.log(myURL.search);// prints ?foo=~bar// Modify the URL via searchParams...myURL.searchParams.sort();console.log(myURL.search);// prints ?foo=%7Ebar
url.username#

Gets and sets the username portion of the URL.

const myURL =newURL('https://abc:xyz@example.com');console.log(myURL.username);// Prints abcmyURL.username ='123';console.log(myURL.href);// Prints https://123:xyz@example.com/

Any invalid URL characters appearing in the value assigned theusernameproperty will bepercent-encoded. The selection of whichcharacters to percent-encode may vary somewhat from what theurl.parse()andurl.format() methods would produce.

url.toString()#

ThetoString() method on theURL object returns the serialized URL. Thevalue returned is equivalent to that ofurl.href andurl.toJSON().

url.toJSON()#
Added in: v7.7.0, v6.13.0

ThetoJSON() method on theURL object returns the serialized URL. Thevalue returned is equivalent to that ofurl.href andurl.toString().

This method is automatically called when anURL object is serializedwithJSON.stringify().

const myURLs = [newURL('https://www.example.com'),newURL('https://test.example.org'),];console.log(JSON.stringify(myURLs));// Prints ["https://www.example.com/","https://test.example.org/"]
URL.createObjectURL(blob)#
History
VersionChanges
v24.0.0, v22.17.0

Marking the API stable.

v16.7.0

Added in: v16.7.0

Creates a'blob:nodedata:...' URL string that represents the given<Blob>object and can be used to retrieve theBlob later.

const {Blob,  resolveObjectURL,} =require('node:buffer');const blob =newBlob(['hello']);const id =URL.createObjectURL(blob);// later...const otherBlob =resolveObjectURL(id);console.log(otherBlob.size);

The data stored by the registered<Blob> will be retained in memory untilURL.revokeObjectURL() is called to remove it.

Blob objects are registered within the current thread. If using WorkerThreads,Blob objects registered within one Worker will not be availableto other workers or the main thread.

URL.revokeObjectURL(id)#
History
VersionChanges
v24.0.0, v22.17.0

Marking the API stable.

v16.7.0

Added in: v16.7.0

  • id<string> A'blob:nodedata:... URL string returned by a prior call toURL.createObjectURL().

Removes the stored<Blob> identified by the given ID. Attempting to revoke aID that isn't registered will silently fail.

URL.canParse(input[, base])#
Added in: v19.9.0, v18.17.0
  • input<string> The absolute or relative input URL to parse. Ifinputis relative, thenbase is required. Ifinput is absolute, thebaseis ignored. Ifinput is not a string, it isconverted to a string first.
  • base<string> The base URL to resolve against if theinput is notabsolute. Ifbase is not a string, it isconverted to a string first.
  • Returns:<boolean>

Checks if aninput relative to thebase can be parsed to aURL.

const isValid =URL.canParse('/foo','https://example.org/');// trueconst isNotValid =URL.canParse('/foo');// false
URL.parse(input[, base])#
Added in: v22.1.0
  • input<string> The absolute or relative input URL to parse. Ifinputis relative, thenbase is required. Ifinput is absolute, thebaseis ignored. Ifinput is not a string, it isconverted to a string first.
  • base<string> The base URL to resolve against if theinput is notabsolute. Ifbase is not a string, it isconverted to a string first.
  • Returns:<URL> |<null>

Parses a string as a URL. Ifbase is provided, it will be used as the baseURL for the purpose of resolving non-absoluteinput URLs. Returnsnullif the parameters can't be resolved to a valid URL.

Class:URLPattern#

Added in: v23.8.0

Stability: 1 - Experimental

TheURLPattern API provides an interface to match URLs or parts of URLsagainst a pattern.

const myPattern =newURLPattern('https://nodejs.org/docs/latest/api/*.html');console.log(myPattern.exec('https://nodejs.org/docs/latest/api/dns.html'));// Prints:// {//  "hash": { "groups": {  "0": "" },  "input": "" },//  "hostname": { "groups": {}, "input": "nodejs.org" },//  "inputs": [//    "https://nodejs.org/docs/latest/api/dns.html"//  ],//  "password": { "groups": { "0": "" }, "input": "" },//  "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },//  "port": { "groups": {}, "input": "" },//  "protocol": { "groups": {}, "input": "https" },//  "search": { "groups": { "0": "" }, "input": "" },//  "username": { "groups": { "0": "" }, "input": "" }// }console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html'));// Prints: true
new URLPattern()#

Instantiate a new emptyURLPattern object.

new URLPattern(string[, baseURL][, options])#

Parse thestring as a URL, and use it to instantiate a newURLPattern object.

IfbaseURL is not specified, it defaults toundefined.

An option can haveignoreCase boolean attribute which enablescase-insensitive matching if set to true.

The constructor can throw aTypeError to indicate parsing failure.

new URLPattern(obj[, baseURL][, options])#

Parse theObject as an input pattern, and use it to instantiate a newURLPattern object. The object members can be any ofprotocol,username,password,hostname,port,pathname,search,hash orbaseURL.

IfbaseURL is not specified, it defaults toundefined.

An option can haveignoreCase boolean attribute which enablescase-insensitive matching if set to true.

The constructor can throw aTypeError to indicate parsing failure.

urlPattern.exec(input[, baseURL])#

Input can be a string or an object providing the individual URL parts. Theobject members can be any ofprotocol,username,password,hostname,port,pathname,search,hash orbaseURL.

IfbaseURL is not specified, it will default toundefined.

Returns an object with aninputs key containing the array of argumentspassed into the function and keys of the URL components which contains thematched input and matched groups.

const myPattern =newURLPattern('https://nodejs.org/docs/latest/api/*.html');console.log(myPattern.exec('https://nodejs.org/docs/latest/api/dns.html'));// Prints:// {//  "hash": { "groups": {  "0": "" },  "input": "" },//  "hostname": { "groups": {}, "input": "nodejs.org" },//  "inputs": [//    "https://nodejs.org/docs/latest/api/dns.html"//  ],//  "password": { "groups": { "0": "" }, "input": "" },//  "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },//  "port": { "groups": {}, "input": "" },//  "protocol": { "groups": {}, "input": "https" },//  "search": { "groups": { "0": "" }, "input": "" },//  "username": { "groups": { "0": "" }, "input": "" }// }
urlPattern.test(input[, baseURL])#

Input can be a string or an object providing the individual URL parts. Theobject members can be any ofprotocol,username,password,hostname,port,pathname,search,hash orbaseURL.

IfbaseURL is not specified, it will default toundefined.

Returns a boolean indicating if the input matches the current pattern.

const myPattern =newURLPattern('https://nodejs.org/docs/latest/api/*.html');console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html'));// Prints: true

Class:URLSearchParams#

History
VersionChanges
v10.0.0

The class is now available on the global object.

v7.5.0, v6.13.0

Added in: v7.5.0, v6.13.0

TheURLSearchParams API provides read and write access to the query of aURL. TheURLSearchParams class can also be used standalone with one of thefour following constructors.TheURLSearchParams class is also available on the global object.

The WHATWGURLSearchParams interface and thequerystring module havesimilar purpose, but the purpose of thequerystring module is moregeneral, as it allows the customization of delimiter characters (& and=).On the other hand, this API is designed purely for URL query strings.

const myURL =newURL('https://example.org/?abc=123');console.log(myURL.searchParams.get('abc'));// Prints 123myURL.searchParams.append('abc','xyz');console.log(myURL.href);// Prints https://example.org/?abc=123&abc=xyzmyURL.searchParams.delete('abc');myURL.searchParams.set('a','b');console.log(myURL.href);// Prints https://example.org/?a=bconst newSearchParams =newURLSearchParams(myURL.searchParams);// The above is equivalent to// const newSearchParams = new URLSearchParams(myURL.search);newSearchParams.append('a','c');console.log(myURL.href);// Prints https://example.org/?a=bconsole.log(newSearchParams.toString());// Prints a=b&a=c// newSearchParams.toString() is implicitly calledmyURL.search = newSearchParams;console.log(myURL.href);// Prints https://example.org/?a=b&a=cnewSearchParams.delete('a');console.log(myURL.href);// Prints https://example.org/?a=b&a=c
new URLSearchParams()#

Instantiate a new emptyURLSearchParams object.

new URLSearchParams(string)#

Parse thestring as a query string, and use it to instantiate a newURLSearchParams object. A leading'?', if present, is ignored.

let params;params =newURLSearchParams('user=abc&query=xyz');console.log(params.get('user'));// Prints 'abc'console.log(params.toString());// Prints 'user=abc&query=xyz'params =newURLSearchParams('?user=abc&query=xyz');console.log(params.toString());// Prints 'user=abc&query=xyz'
new URLSearchParams(obj)#
Added in: v7.10.0, v6.13.0
  • obj<Object> An object representing a collection of key-value pairs

Instantiate a newURLSearchParams object with a query hash map. The key andvalue of each property ofobj are always coerced to strings.

Unlikequerystring module, duplicate keys in the form of array values arenot allowed. Arrays are stringified usingarray.toString(), which simplyjoins all array elements with commas.

const params =newURLSearchParams({user:'abc',query: ['first','second'],});console.log(params.getAll('query'));// Prints [ 'first,second' ]console.log(params.toString());// Prints 'user=abc&query=first%2Csecond'
new URLSearchParams(iterable)#
Added in: v7.10.0, v6.13.0
  • iterable<Iterable> An iterable object whose elements are key-value pairs

Instantiate a newURLSearchParams object with an iterable map in a way thatis similar to<Map>'s constructor.iterable can be anArray or anyiterable object. That meansiterable can be anotherURLSearchParams, inwhich case the constructor will simply create a clone of the providedURLSearchParams. Elements ofiterable are key-value pairs, and canthemselves be any iterable object.

Duplicate keys are allowed.

let params;// Using an arrayparams =newURLSearchParams([  ['user','abc'],  ['query','first'],  ['query','second'],]);console.log(params.toString());// Prints 'user=abc&query=first&query=second'// Using a Map objectconst map =newMap();map.set('user','abc');map.set('query','xyz');params =newURLSearchParams(map);console.log(params.toString());// Prints 'user=abc&query=xyz'// Using a generator functionfunction*getQueryPairs() {yield ['user','abc'];yield ['query','first'];yield ['query','second'];}params =newURLSearchParams(getQueryPairs());console.log(params.toString());// Prints 'user=abc&query=first&query=second'// Each key-value pair must have exactly two elementsnewURLSearchParams([  ['user','abc','error'],]);// Throws TypeError [ERR_INVALID_TUPLE]://        Each query pair must be an iterable [name, value] tuple
urlSearchParams.append(name, value)#

Append a new name-value pair to the query string.

urlSearchParams.delete(name[, value])#
History
VersionChanges
v20.2.0, v18.18.0

Add support for optionalvalue argument.

Ifvalue is provided, removes all name-value pairswhere name isname and value isvalue..

Ifvalue is not provided, removes all name-value pairs whose name isname.

urlSearchParams.entries()#

Returns an ES6Iterator over each of the name-value pairs in the query.Each item of the iterator is a JavaScriptArray. The first item of theArrayis thename, the second item of theArray is thevalue.

Alias forurlSearchParams[Symbol.iterator]().

urlSearchParams.forEach(fn[, thisArg])#
History
VersionChanges
v18.0.0

Passing an invalid callback to thefn argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

  • fn<Function> Invoked for each name-value pair in the query
  • thisArg<Object> To be used asthis value for whenfn is called

Iterates over each name-value pair in the query and invokes the given function.

const myURL =newURL('https://example.org/?a=b&c=d');myURL.searchParams.forEach((value, name, searchParams) => {console.log(name, value, myURL.searchParams === searchParams);});// Prints://   a b true//   c d true
urlSearchParams.get(name)#

Returns the value of the first name-value pair whose name isname. If thereare no such pairs,null is returned.

urlSearchParams.getAll(name)#

Returns the values of all name-value pairs whose name isname. If there areno such pairs, an empty array is returned.

urlSearchParams.has(name[, value])#
History
VersionChanges
v20.2.0, v18.18.0

Add support for optionalvalue argument.

Checks if theURLSearchParams object contains key-value pair(s) based onname and an optionalvalue argument.

Ifvalue is provided, returnstrue when name-value pair withsamename andvalue exists.

Ifvalue is not provided, returnstrue if there is at least one name-valuepair whose name isname.

urlSearchParams.keys()#

Returns an ES6Iterator over the names of each name-value pair.

const params =newURLSearchParams('foo=bar&foo=baz');for (const nameof params.keys()) {console.log(name);}// Prints://   foo//   foo
urlSearchParams.set(name, value)#

Sets the value in theURLSearchParams object associated withname tovalue. If there are any pre-existing name-value pairs whose names arename,set the first such pair's value tovalue and remove all others. If not,append the name-value pair to the query string.

const params =newURLSearchParams();params.append('foo','bar');params.append('foo','baz');params.append('abc','def');console.log(params.toString());// Prints foo=bar&foo=baz&abc=defparams.set('foo','def');params.set('xyz','opq');console.log(params.toString());// Prints foo=def&abc=def&xyz=opq
urlSearchParams.size#
Added in: v19.8.0, v18.16.0

The total number of parameter entries.

urlSearchParams.sort()#
Added in: v7.7.0, v6.13.0

Sort all existing name-value pairs in-place by their names. Sorting is donewith astable sorting algorithm, so relative order between name-value pairswith the same name is preserved.

This method can be used, in particular, to increase cache hits.

const params =newURLSearchParams('query[]=abc&type=search&query[]=123');params.sort();console.log(params.toString());// Prints query%5B%5D=abc&query%5B%5D=123&type=search
urlSearchParams.toString()#

Returns the search parameters serialized as a string, with characterspercent-encoded where necessary.

urlSearchParams.values()#

Returns an ES6Iterator over the values of each name-value pair.

urlSearchParams[Symbol.iterator]()#

Returns an ES6Iterator over each of the name-value pairs in the query string.Each item of the iterator is a JavaScriptArray. The first item of theArrayis thename, the second item of theArray is thevalue.

Alias forurlSearchParams.entries().

const params =newURLSearchParams('foo=bar&xyz=baz');for (const [name, value]of params) {console.log(name, value);}// Prints://   foo bar//   xyz baz

url.domainToASCII(domain)#

History
VersionChanges
v20.0.0, v18.17.0

ICU requirement is removed.

v7.4.0, v6.13.0

Added in: v7.4.0, v6.13.0

Returns thePunycode ASCII serialization of thedomain. Ifdomain is aninvalid domain, the empty string is returned.

It performs the inverse operation tourl.domainToUnicode().

import urlfrom'node:url';console.log(url.domainToASCII('español.com'));// Prints xn--espaol-zwa.comconsole.log(url.domainToASCII('中文.com'));// Prints xn--fiq228c.comconsole.log(url.domainToASCII('xn--iñvalid.com'));// Prints an empty stringconst url =require('node:url');console.log(url.domainToASCII('español.com'));// Prints xn--espaol-zwa.comconsole.log(url.domainToASCII('中文.com'));// Prints xn--fiq228c.comconsole.log(url.domainToASCII('xn--iñvalid.com'));// Prints an empty string

url.domainToUnicode(domain)#

History
VersionChanges
v20.0.0, v18.17.0

ICU requirement is removed.

v7.4.0, v6.13.0

Added in: v7.4.0, v6.13.0

Returns the Unicode serialization of thedomain. Ifdomain is an invaliddomain, the empty string is returned.

It performs the inverse operation tourl.domainToASCII().

import urlfrom'node:url';console.log(url.domainToUnicode('xn--espaol-zwa.com'));// Prints español.comconsole.log(url.domainToUnicode('xn--fiq228c.com'));// Prints 中文.comconsole.log(url.domainToUnicode('xn--iñvalid.com'));// Prints an empty stringconst url =require('node:url');console.log(url.domainToUnicode('xn--espaol-zwa.com'));// Prints español.comconsole.log(url.domainToUnicode('xn--fiq228c.com'));// Prints 中文.comconsole.log(url.domainToUnicode('xn--iñvalid.com'));// Prints an empty string

url.fileURLToPath(url[, options])#

History
VersionChanges
v22.1.0, v20.13.0

Theoptions argument can now be used to determine how to parse thepath argument.

v10.12.0

Added in: v10.12.0

  • url<URL> |<string> The file URL string or URL object to convert to a path.
  • options<Object>
    • windows<boolean> |<undefined>true if thepath should bereturn as a windows filepath,false for posix, andundefined for the system default.Default:undefined.
  • Returns:<string> The fully-resolved platform-specific Node.js file path.

This function ensures the correct decodings of percent-encoded characters aswell as ensuring a cross-platform valid absolute path string.

import { fileURLToPath }from'node:url';const __filename =fileURLToPath(import.meta.url);newURL('file:///C:/path/').pathname;// Incorrect: /C:/path/fileURLToPath('file:///C:/path/');// Correct:   C:\path\ (Windows)newURL('file://nas/foo.txt').pathname;// Incorrect: /foo.txtfileURLToPath('file://nas/foo.txt');// Correct:   \\nas\foo.txt (Windows)newURL('file:///你好.txt').pathname;// Incorrect: /%E4%BD%A0%E5%A5%BD.txtfileURLToPath('file:///你好.txt');// Correct:   /你好.txt (POSIX)newURL('file:///hello world').pathname;// Incorrect: /hello%20worldfileURLToPath('file:///hello world');// Correct:   /hello world (POSIX)const { fileURLToPath } =require('node:url');newURL('file:///C:/path/').pathname;// Incorrect: /C:/path/fileURLToPath('file:///C:/path/');// Correct:   C:\path\ (Windows)newURL('file://nas/foo.txt').pathname;// Incorrect: /foo.txtfileURLToPath('file://nas/foo.txt');// Correct:   \\nas\foo.txt (Windows)newURL('file:///你好.txt').pathname;// Incorrect: /%E4%BD%A0%E5%A5%BD.txtfileURLToPath('file:///你好.txt');// Correct:   /你好.txt (POSIX)newURL('file:///hello world').pathname;// Incorrect: /hello%20worldfileURLToPath('file:///hello world');// Correct:   /hello world (POSIX)

url.fileURLToPathBuffer(url[, options])#

  • url<URL> |<string> The file URL string or URL object to convert to a path.
  • options<Object>
    • windows<boolean> |<undefined>true if thepath should bereturn as a windows filepath,false for posix, andundefined for the system default.Default:undefined.
  • Returns:<Buffer> The fully-resolved platform-specific Node.js file pathas a<Buffer>.

Likeurl.fileURLToPath(...) except that instead of returning a stringrepresentation of the path, aBuffer is returned. This conversion ishelpful when the input URL contains percent-encoded segments that arenot valid UTF-8 / Unicode sequences.

url.format(URL[, options])#

Added in: v7.6.0
  • URL<URL> AWHATWG URL object
  • options<Object>
    • auth<boolean>true if the serialized URL string should include theusername and password,false otherwise.Default:true.
    • fragment<boolean>true if the serialized URL string should include thefragment,false otherwise.Default:true.
    • search<boolean>true if the serialized URL string should include thesearch query,false otherwise.Default:true.
    • unicode<boolean>true if Unicode characters appearing in the hostcomponent of the URL string should be encoded directly as opposed to beingPunycode encoded.Default:false.
  • Returns:<string>

Returns a customizable serialization of a URLString representation of aWHATWG URL object.

The URL object has both atoString() method andhref property that returnstring serializations of the URL. These are not, however, customizable inany way. Theurl.format(URL[, options]) method allows for basic customizationof the output.

import urlfrom'node:url';const myURL =newURL('https://a:b@測試?abc#foo');console.log(myURL.href);// Prints https://a:b@xn--g6w251d/?abc#fooconsole.log(myURL.toString());// Prints https://a:b@xn--g6w251d/?abc#fooconsole.log(url.format(myURL, {fragment:false,unicode:true,auth:false }));// Prints 'https://測試/?abc'const url =require('node:url');const myURL =newURL('https://a:b@測試?abc#foo');console.log(myURL.href);// Prints https://a:b@xn--g6w251d/?abc#fooconsole.log(myURL.toString());// Prints https://a:b@xn--g6w251d/?abc#fooconsole.log(url.format(myURL, {fragment:false,unicode:true,auth:false }));// Prints 'https://測試/?abc'

url.pathToFileURL(path[, options])#

History
VersionChanges
v22.1.0, v20.13.0

Theoptions argument can now be used to determine how to return thepath value.

v10.12.0

Added in: v10.12.0

  • path<string> The path to convert to a File URL.
  • options<Object>
    • windows<boolean> |<undefined>true if thepath should betreated as a windows filepath,false for posix, andundefined for the system default.Default:undefined.
  • Returns:<URL> The file URL object.

This function ensures thatpath is resolved absolutely, and that the URLcontrol characters are correctly encoded when converting into a File URL.

import { pathToFileURL }from'node:url';newURL('/foo#1','file:');// Incorrect: file:///foo#1pathToFileURL('/foo#1');// Correct:   file:///foo%231 (POSIX)newURL('/some/path%.c','file:');// Incorrect: file:///some/path%.cpathToFileURL('/some/path%.c');// Correct:   file:///some/path%25.c (POSIX)const { pathToFileURL } =require('node:url');newURL(__filename);// Incorrect: throws (POSIX)newURL(__filename);// Incorrect: C:\... (Windows)pathToFileURL(__filename);// Correct:   file:///... (POSIX)pathToFileURL(__filename);// Correct:   file:///C:/... (Windows)newURL('/foo#1','file:');// Incorrect: file:///foo#1pathToFileURL('/foo#1');// Correct:   file:///foo%231 (POSIX)newURL('/some/path%.c','file:');// Incorrect: file:///some/path%.cpathToFileURL('/some/path%.c');// Correct:   file:///some/path%25.c (POSIX)

url.urlToHttpOptions(url)#

History
VersionChanges
v19.9.0, v18.17.0

The returned object will also contain all the own enumerable properties of theurl argument.

v15.7.0, v14.18.0

Added in: v15.7.0, v14.18.0

  • url<URL> TheWHATWG URL object to convert to an options object.
  • Returns:<Object> Options object
    • protocol<string> Protocol to use.
    • hostname<string> A domain name or IP address of the server to issue therequest to.
    • hash<string> The fragment portion of the URL.
    • search<string> The serialized query portion of the URL.
    • pathname<string> The path portion of the URL.
    • path<string> Request path. Should include query string if any.E.G.'/index.html?page=12'. An exception is thrown when the request pathcontains illegal characters. Currently, only spaces are rejected but thatmay change in the future.
    • href<string> The serialized URL.
    • port<number> Port of remote server.
    • auth<string> Basic authentication i.e.'user:password' to compute anAuthorization header.

This utility function converts a URL object into an ordinary options object asexpected by thehttp.request() andhttps.request() APIs.

import { urlToHttpOptions }from'node:url';const myURL =newURL('https://a:b@測試?abc#foo');console.log(urlToHttpOptions(myURL));/*{  protocol: 'https:',  hostname: 'xn--g6w251d',  hash: '#foo',  search: '?abc',  pathname: '/',  path: '/?abc',  href: 'https://a:b@xn--g6w251d/?abc#foo',  auth: 'a:b'}*/const { urlToHttpOptions } =require('node:url');const myURL =newURL('https://a:b@測試?abc#foo');console.log(urlToHttpOptions(myURL));/*{  protocol: 'https:',  hostname: 'xn--g6w251d',  hash: '#foo',  search: '?abc',  pathname: '/',  path: '/?abc',  href: 'https://a:b@xn--g6w251d/?abc#foo',  auth: 'a:b'}*/

Legacy URL API#

History
VersionChanges
v15.13.0, v14.17.0

Deprecation revoked. Status changed to "Legacy".

v11.0.0

This API is deprecated.

Stability: 3 - Legacy: Use the WHATWG URL API instead.

LegacyurlObject#

History
VersionChanges
v15.13.0, v14.17.0

Deprecation revoked. Status changed to "Legacy".

v11.0.0

The Legacy URL API is deprecated. Use the WHATWG URL API.

The legacyurlObject (require('node:url').Url orimport { Url } from 'node:url') iscreated and returned by theurl.parse() function.

urlObject.auth#

Theauth property is the username and password portion of the URL, alsoreferred to asuserinfo. This string subset follows theprotocol anddouble slashes (if present) and precedes thehost component, delimited by@.The string is either the username, or it is the username and password separatedby:.

For example:'user:pass'.

urlObject.hash#

Thehash property is the fragment identifier portion of the URL including theleading# character.

For example:'#hash'.

urlObject.host#

Thehost property is the full lower-cased host portion of the URL, includingtheport if specified.

For example:'sub.example.com:8080'.

urlObject.hostname#

Thehostname property is the lower-cased host name portion of thehostcomponentwithout theport included.

For example:'sub.example.com'.

urlObject.href#

Thehref property is the full URL string that was parsed with both theprotocol andhost components converted to lower-case.

For example:'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.

urlObject.path#

Thepath property is a concatenation of thepathname andsearchcomponents.

For example:'/p/a/t/h?query=string'.

No decoding of thepath is performed.

urlObject.pathname#

Thepathname property consists of the entire path section of the URL. Thisis everything following thehost (including theport) and before the startof thequery orhash components, delimited by either the ASCII questionmark (?) or hash (#) characters.

For example:'/p/a/t/h'.

No decoding of the path string is performed.

urlObject.port#

Theport property is the numeric port portion of thehost component.

For example:'8080'.

urlObject.protocol#

Theprotocol property identifies the URL's lower-cased protocol scheme.

For example:'http:'.

urlObject.query#

Thequery property is either the query string without the leading ASCIIquestion mark (?), or an object returned by thequerystring module'sparse() method. Whether thequery property is a string or object isdetermined by theparseQueryString argument passed tourl.parse().

For example:'query=string' or{'query': 'string'}.

If returned as a string, no decoding of the query string is performed. Ifreturned as an object, both keys and values are decoded.

urlObject.search#

Thesearch property consists of the entire "query string" portion of theURL, including the leading ASCII question mark (?) character.

For example:'?query=string'.

No decoding of the query string is performed.

urlObject.slashes#

Theslashes property is aboolean with a value oftrue if two ASCIIforward-slash characters (/) are required following the colon in theprotocol.

url.format(urlObject)#

History
VersionChanges
v17.0.0

Now throws anERR_INVALID_URL exception when Punycode conversion of a hostname introduces changes that could cause the URL to be re-parsed differently.

v15.13.0, v14.17.0

Deprecation revoked. Status changed to "Legacy".

v11.0.0

The Legacy URL API is deprecated. Use the WHATWG URL API.

v7.0.0

URLs with afile: scheme will now always use the correct number of slashes regardless ofslashes option. A falsyslashes option with no protocol is now also respected at all times.

v0.1.25

Added in: v0.1.25

  • urlObject<Object> |<string> A URL object (as returned byurl.parse() orconstructed otherwise). If a string, it is converted to an object by passingit tourl.parse().

Theurl.format() method returns a formatted URL string derived fromurlObject.

const url =require('node:url');url.format({protocol:'https',hostname:'example.com',pathname:'/some/path',query: {page:1,format:'json',  },});// => 'https://example.com/some/path?page=1&format=json'

IfurlObject is not an object or a string,url.format() will throw aTypeError.

The formatting process operates as follows:

  • A new empty stringresult is created.
  • IfurlObject.protocol is a string, it is appended as-is toresult.
  • Otherwise, ifurlObject.protocol is notundefined and is not a string, anError is thrown.
  • For all string values ofurlObject.protocol thatdo not end with an ASCIIcolon (:) character, the literal string: will be appended toresult.
  • If either of the following conditions is true, then the literal string//will be appended toresult:
    • urlObject.slashes property is true;
    • urlObject.protocol begins withhttp,https,ftp,gopher, orfile;
  • If the value of theurlObject.auth property is truthy, and eitherurlObject.host orurlObject.hostname are notundefined, the value ofurlObject.auth will be coerced into a string and appended toresultfollowed by the literal string@.
  • If theurlObject.host property isundefined then:
    • If theurlObject.hostname is a string, it is appended toresult.
    • Otherwise, ifurlObject.hostname is notundefined and is not a string,anError is thrown.
    • If theurlObject.port property value is truthy, andurlObject.hostnameis notundefined:
      • The literal string: is appended toresult, and
      • The value ofurlObject.port is coerced to a string and appended toresult.
  • Otherwise, if theurlObject.host property value is truthy, the value ofurlObject.host is coerced to a string and appended toresult.
  • If theurlObject.pathname property is a string that is not an empty string:
    • If theurlObject.pathnamedoes not start with an ASCII forward slash(/), then the literal string'/' is appended toresult.
    • The value ofurlObject.pathname is appended toresult.
  • Otherwise, ifurlObject.pathname is notundefined and is not a string, anError is thrown.
  • If theurlObject.search property isundefined and if theurlObject.queryproperty is anObject, the literal string? is appended toresultfollowed by the output of calling thequerystring module'sstringify()method passing the value ofurlObject.query.
  • Otherwise, ifurlObject.search is a string:
    • If the value ofurlObject.searchdoes not start with the ASCII questionmark (?) character, the literal string? is appended toresult.
    • The value ofurlObject.search is appended toresult.
  • Otherwise, ifurlObject.search is notundefined and is not a string, anError is thrown.
  • If theurlObject.hash property is a string:
    • If the value ofurlObject.hashdoes not start with the ASCII hash (#)character, the literal string# is appended toresult.
    • The value ofurlObject.hash is appended toresult.
  • Otherwise, if theurlObject.hash property is notundefined and is not astring, anError is thrown.
  • result is returned.

An automated migration is available (source).

npx codemod@latest @nodejs/node-url-to-whatwg-url

url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#

History
VersionChanges
v19.0.0, v18.13.0

Documentation-only deprecation.

v15.13.0, v14.17.0

Deprecation revoked. Status changed to "Legacy".

v11.14.0

Thepathname property on the returned URL object is now/ when there is no path and the protocol scheme isws: orwss:.

v11.0.0

The Legacy URL API is deprecated. Use the WHATWG URL API.

v9.0.0

Thesearch property on the returned URL object is nownull when no query string is present.

v0.1.25

Added in: v0.1.25

Stability: 0 - Deprecated: Use the WHATWG URL API instead.

  • urlString<string> The URL string to parse.
  • parseQueryString<boolean> Iftrue, thequery property will alwaysbe set to an object returned by thequerystring module'sparse()method. Iffalse, thequery property on the returned URL object will be anunparsed, undecoded string.Default:false.
  • slashesDenoteHost<boolean> Iftrue, the first token after the literalstring// and preceding the next/ will be interpreted as thehost.For instance, given//foo/bar, the result would be{host: 'foo', pathname: '/bar'} rather than{pathname: '//foo/bar'}.Default:false.

Theurl.parse() method takes a URL string, parses it, and returns a URLobject.

ATypeError is thrown ifurlString is not a string.

AURIError is thrown if theauth property is present but cannot be decoded.

url.parse() uses a lenient, non-standard algorithm for parsing URLstrings. It is prone to security issues such ashost name spoofingand incorrect handling of usernames and passwords. Do not use with untrustedinput. CVEs are not issued forurl.parse() vulnerabilities. Use theWHATWG URL API instead, for example:

functiongetURL(req) {const proto = req.headers['x-forwarded-proto'] ||'https';const host = req.headers['x-forwarded-host'] || req.headers.host ||'example.com';returnnewURL(`${proto}://${host}${req.url ||'/'}`);}

The example above assumes well-formed headers are forwarded from a reverseproxy to your Node.js server. If you are not using a reverse proxy, you shoulduse the example below:

functiongetURL(req) {returnnewURL(`https://example.com${req.url ||'/'}`);}

An automated migration is available (source).

npx codemod@latest @nodejs/node-url-to-whatwg-url

url.resolve(from, to)#

History
VersionChanges
v15.13.0, v14.17.0

Deprecation revoked. Status changed to "Legacy".

v11.0.0

The Legacy URL API is deprecated. Use the WHATWG URL API.

v6.6.0

Theauth fields are now kept intact whenfrom andto refer to the same host.

v6.0.0

Theauth fields is cleared now theto parameter contains a hostname.

v6.5.0, v4.6.2

Theport field is copied correctly now.

v0.1.25

Added in: v0.1.25

  • from<string> The base URL to use ifto is a relative URL.
  • to<string> The target URL to resolve.

Theurl.resolve() method resolves a target URL relative to a base URL in amanner similar to that of a web browser resolving an anchor tag.

const url =require('node:url');url.resolve('/one/two/three','four');// '/one/two/four'url.resolve('http://example.com/','/one');// 'http://example.com/one'url.resolve('http://example.com/one','/two');// 'http://example.com/two'

To achieve the same result using the WHATWG URL API:

functionresolve(from, to) {const resolvedUrl =newURL(to,newURL(from,'resolve://'));if (resolvedUrl.protocol ==='resolve:') {// `from` is a relative URL.const { pathname, search, hash } = resolvedUrl;return pathname + search + hash;  }return resolvedUrl.toString();}resolve('/one/two/three','four');// '/one/two/four'resolve('http://example.com/','/one');// 'http://example.com/one'resolve('http://example.com/one','/two');// 'http://example.com/two'

Percent-encoding in URLs#

URLs are permitted to only contain a certain range of characters. Any characterfalling outside of that range must be encoded. How such characters are encoded,and which characters to encode depends entirely on where the character islocated within the structure of the URL.

Legacy API#

Within the Legacy API, spaces (' ') and the following characters will beautomatically escaped in the properties of URL objects:

< > " ` \r \n \t { } | \ ^ '

For example, the ASCII space character (' ') is encoded as%20. The ASCIIforward slash (/) character is encoded as%3C.

WHATWG API#

TheWHATWG URL Standard uses a more selective and fine grained approach toselecting encoded characters than that used by the Legacy API.

The WHATWG algorithm defines four "percent-encode sets" that describe rangesof characters that must be percent-encoded:

  • TheC0 control percent-encode set includes code points in range U+0000 toU+001F (inclusive) and all code points greater than U+007E (~).

  • Thefragment percent-encode set includes theC0 control percent-encode setand code points U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>),and U+0060 (`).

  • Thepath percent-encode set includes theC0 control percent-encode setand code points U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), U+003E (>),U+003F (?), U+0060 (`), U+007B ({), and U+007D (}).

  • Theuserinfo encode set includes thepath percent-encode set and codepoints U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@),U+005B ([) to U+005E(^), and U+007C (|).

Theuserinfo percent-encode set is used exclusively for username andpasswords encoded within the URL. Thepath percent-encode set is used for thepath of most URLs. Thefragment percent-encode set is used for URL fragments.TheC0 control percent-encode set is used for host and path under certainspecific conditions, in addition to all other cases.

When non-ASCII characters appear within a host name, the host name is encodedusing thePunycode algorithm. Note, however, that a host namemay containboth Punycode encoded and percent-encoded characters:

const myURL =newURL('https://%CF%80.example.com/foo');console.log(myURL.href);// Prints https://xn--1xa.example.com/fooconsole.log(myURL.origin);// Prints https://xn--1xa.example.com