Get The Current Domain Name With Javascript (Not the path, etc.)

Learn get the current domain name with javascript (not the path, etc.) with practical examples, diagrams, and best practices. Covers javascript, domain-name development techniques with visual expla...

How to Get the Current Domain Name with JavaScript

Hero image for Get The Current Domain Name With Javascript (Not the path, etc.)

Learn various JavaScript methods to accurately extract the current domain name from the browser's URL, excluding paths, query parameters, and fragments.

When working with web applications, it's often necessary to programmatically determine the current domain name. This is crucial for tasks like dynamic API calls, cross-origin communication checks, or simply displaying the host information to the user. While the browser's window.location object provides a wealth of URL-related properties, pinpointing just the domain name (e.g., example.com from https://example.com/path?query=1#hash) requires understanding which properties to use and how to handle potential variations.

Understanding the window.location Object

The window.location object is a powerful interface that provides information about the current URL and allows for navigation. It exposes several properties, each representing a different part of the URL. For extracting the domain name, we'll primarily focus on hostname and origin.

graph TD
    A[window.location] --> B(protocol)
    A --> C(hostname)
    A --> D(port)
    A --> E(pathname)
    A --> F(search)
    A --> G(hash)
    A --> H(href)
    A --> I(origin)
    C -- "Domain Name" --> J[Target: example.com]
    I -- "Protocol + Domain + Port" --> K[Target: https://example.com:8080]

Breakdown of window.location properties and their relation to the domain.

Method 1: Using window.location.hostname

The hostname property of the window.location object directly returns the domain name or IP address of the server. This is often the most straightforward and preferred method when you need just the domain without the protocol or port number.

const domainName = window.location.hostname;
console.log(domainName); // e.g., 'www.example.com' or 'localhost'

Retrieving the domain name using window.location.hostname.

Method 2: Using window.location.origin (with caution)

The origin property returns the protocol, hostname, and port number of the URL. While it includes the domain, it also includes the protocol and port, which might not be what you want if you strictly need only the domain name. However, it's useful for understanding the full origin for security contexts like CORS.

const fullOrigin = window.location.origin;
console.log(fullOrigin); // e.g., 'https://www.example.com:8080' or 'http://localhost:3000'

// To extract just the hostname from origin:
const domainFromOrigin = new URL(fullOrigin).hostname;
console.log(domainFromOrigin); // e.g., 'www.example.com' or 'localhost'

Using window.location.origin and then parsing with URL to get the hostname.

Handling Edge Cases and Subdomains

Sometimes you might need to extract the 'root' domain, excluding subdomains like www. This requires a bit more manipulation, as hostname includes the full host. A common approach is to split the hostname by dots and take the last two parts, but this can be tricky with country code top-level domains (ccTLDs) like .co.uk.

function getRootDomain(hostname) {
  const parts = hostname.split('.');
  if (parts.length <= 2) {
    return hostname; // e.g., 'localhost', 'example.com'
  }
  // Simple heuristic: assumes TLDs are 2 parts (e.g., .com, .org)
  // This is NOT foolproof for all ccTLDs like .co.uk
  return parts.slice(-2).join('.');
}

const currentHostname = window.location.hostname;
const rootDomain = getRootDomain(currentHostname);

console.log(`Full Hostname: ${currentHostname}`); // e.g., 'sub.example.com'
console.log(`Root Domain (simple): ${rootDomain}`); // e.g., 'example.com'

A simple function to attempt to extract the root domain, with limitations.