Node.js: Get domain, hostname, and protocol from a URL
( 64 Articles)
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, kindacode.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.kindacode.com, subdomain.kindacode.com consists of local hostnames (www and subdomain), and the domain kindacode.com.
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).
// Replace this with your own url const myUrl = 'https://www.kindacode.com/article/how-to-get-all-links-from-a-webpage-using-node-js/'; 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);
Hostname: www.kindacode.com Domain: kindacode.com 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:
- Using Axios to download files in Node.js
- Node.js: Get File Name and Extension from Path/URL
- Node + Mongoose + TypeScript: Defining Schemas and Models
- Node.js: Reading and Parsing Excel (XLSX) Files
- How to get all Links from a Webpage using Node.js
- How to generate slugs from titles in Node.js
You can also check out our Node.js category page for the latest tutorials and examples.