The recently released version 8.0.0 of Node.js made the experimental implementation of the WHATWG URL parser from Node.js v7.0.0 non-experimental and fully supported. Here’s what you can use it for.

A URL like http://www.example.com/foo?bar=1#main consists of several different parts - e.g., the host part (www.example.com) or the search (?bar=1, often called query string).

When writing Node.js web server software, you regularly need to access or even manipulate those different parts. While this can be achieved by working with the URL as a simple string, splitting this string into its different logical parts manually with substring operations or regular expressions is very cumbersome. A dedicated library makes this very easy.

You have already been able to parse URLs in Node.js before, via the url module, but this provided a very Node.js specific implementation which is now considered legacy.

The url module now provides an additional implementation which implements the standardized WHATWG URL API, making the url-parsing code of Node.js work identical to the way that web browsers are parsing URLs.

The new API is based on the URL object, which makes the different parts of a URL available as object attributes:

var URL = require('url').URL;
var myURL = new URL('http://www.example.com/foo?bar=1#main');

console.log(myURL.host);

// prints 'www.example.com'

Here is an overview of all the different parts of an URL and how the according URL object attribute is named:

"  https:   //  user : pass @ sub.host.com : 80   /p/a/t/h  ?  query=string   #hash "
│          │  │      │      │   hostname   │port│          │                │       │
│          │  │ user-│ pass-├──────────────┴────┤          │                │       │
│ protocol │  │ name │ word │        host       │          │                │       │
├──────────┴──┼──────┴──────┼───────────────────┤          │                │       │
│   origin    │             │       origin      │ pathname │     search     │ hash  │
├─────────────┴─────────────┴───────────────────┴──────────┴────────────────┴───────┤
│                                    href                                           │
└───────────────────────────────────────────────────────────────────────────────────┘

The URL object representation of a URL can also be used to change those parts:

var URL = require('url').URL;
var myURL = new URL('http://www.example.com/foo?bar=1#main');

myURL.protocol = 'https';

myURL.search = '?newBar=2';

console.log(myURL.href);

// prints 'https://www.example.com/foo?newBar=2#main'

Learn more about working with URLs and building your own web server application with Node.js with The Node Beginner Book - the first part of this extensive Node.js tutorial is available for free!