Node.js: Get domain, hostname, and protocol from a URL

Last updated on March 19, 2022 Guest Contributor Loading... Post a comment

By using the URL class, a built-in module of Node.js, we can easily extract domain/hostname and protocol from a given url without using any third-party package.

Domain, hostname, and protocol

A domain name is the address of a website that people type in the browser URL bar to visit your website. For example, is a domain name.

A hostname is a domain name assigned to a host computer. This is usually a combination of the host’s local name with its parent domain’s name. For example, consists of local hostnames (www and subdomain), and the domain

An internet protocol is a defined set of rules and regulations that determine how data is transmitted in telecommunications and computer networking. For example, WebSocket, HTTP, HTTPS are protocols.

Node.js URL API

The URL class was first added in Node.js 6.13. From Node.js 10.0 and up, the class is available on the global object so you can use it without this line:

const URL = require('url'); 
// This is no longer necessary for Node 10.0+

Create a URL object from a string URL:

const urlObject = new URL('a-string-URL-here');

The URL object comes with some properties including hostname, protocol, port, pathname, hash, host, href, origin, password, pathname, search, searchParams, username.

In some cases, the domain name may be different from the hostname and we need to use a regular expression to get the correct domain name (you can see this in the example below).


The code:

// Replace this with your own url
const myUrl =

const urlObject = new URL(myUrl);
const hostName = urlObject.hostname;

// The regular expression below works with .com, .net, .org and other top level domain names
let domainName = hostName.replace(/^[^.]+\./g, '');

const protocol = urlObject.protocol;

console.log('Hostname:', hostName);
console.log('Domain:', domainName);
console.log('Protocol:', protocol);


Protocol: https:


In this article, we learned about how to get domain, hostname, protocol from a URL without any third-party module. If you would like to learn more about Node.js, take a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles