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.
Table of Contents
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, slingacademy.com
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, www.slingacademy.com
, api.slingacademy.com
consists of local hostnames (www
and api
), and the domain slingacademy.com
.
An internet protocol is a defined set of rules and regulations that determine how data is transmitted in telecommunications and computer networking. For instance, WebSocket, HTTP, and HTTPS are protocols.
Node.js URL API
The URL class was first added in Node.js 6.13. From Node.js 10.0 and above, 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
, and 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).
Example
The code:
// Replace this with your own url
const myUrl =
'https://www.slingacademy.com/article/how-to-set-up-typescript-for-a-node-js-project/';
const urlObject = new URL(myUrl);
const hostName = urlObject.hostname;
// The regular expression below works with .dev, .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);
Output:
Hostname: www.slingacademy.com
Domain: slingacademy.com
Protocol: https:
That’s it. Happy coding!