What is a Hostname?
A hostname is the textual label that identifies a specific device, server, or domain on a network. In the context of web development and URLs, the hostname is the portion between the protocol (like https://) and the port number or path. For example, in the URL https://www.example.com/products/page, the hostname is www.example.com.
Hostnames serve as human-readable identifiers that map to IP addresses, making it easier for users and developers to access resources without memorizing numeric addresses. A hostname can represent a domain name (like example.com), a subdomain (like api.example.com), or even an IP address in certain contexts.
Hostname vs Domain Name
While often used interchangeably, there's a subtle distinction: every hostname is technically a domain name, but not all domain names qualify as hostnames in their full form. A hostname includes any subdomain levels, so api.example.com has the hostname api.example.com, while the domain name is simply example.com. The registered domain represents the core brand identity, while subdomains typically serve organizational or technical purposes like routing, staging environments, or service isolation.
In modern web development, understanding this distinction becomes crucial when building multi-tenant applications or implementing subdomain-based architectures.
https:// www.example.com /products/page ?category=books
──────────── ──────────────────── ───────────── ─────────
protocol hostname pathname searchGetting Hostname from the Current Page
The most common use case for hostname extraction is retrieving the domain of the page the user is currently viewing. The window.location.hostname property provides direct access to this information without any parsing or transformation required. This property belongs to the browser's Location interface, which comprehensively represents the current URL and its components.
This approach is ideal for conditional logic based on the current domain, such as displaying region-specific content, implementing A/B tests across domains, or enabling cross-origin security checks. It's the most straightforward method when you only need the hostname of the active page. For developers working on professional web applications, this technique forms the foundation of many domain-aware features.
// Get hostname of current page
const currentHostname = window.location.hostname;
console.log(currentHostname); // "www.example.com"
You can also access this via document.location.hostname, which provides identical functionality. The window.location approach is generally preferred as it's more explicit and works consistently across browser environments.
The Location interface provides several properties to access different parts of a URL
hostname
The domain name or IP address of the URL (e.g., "www.example.com")
host
Hostname plus port number (e.g., "www.example.com:443")
protocol
The URL protocol including the colon (e.g., "https:")
pathname
The path portion of the URL starting with a forward slash
console.log(window.location.hostname); // "www.example.com"
console.log(window.location.host); // "www.example.com:443"
console.log(window.location.protocol); // "https:"
console.log(window.location.pathname); // "/products/page"
console.log(window.location.search); // "?category=books"Extracting Hostname from URL Strings
When you need to extract hostnames from arbitrary URL strings rather than the current page, the URL() constructor provides the most reliable and standards-compliant approach. Unlike location.hostname, which only works with the current page's URL, the URL() constructor can parse any valid URL string, making it essential for processing user input, API responses, or external links.
This method offers significant advantages over manual string parsing or regular expressions: it includes built-in validation, handles edge cases automatically, and provides consistent behavior across all modern browsers and Node.js environments. The parsed URL object gives you type-safe access to every component of the URL. For developers building modern JavaScript applications, mastering URL parsing is an essential skill.
// Create URL object and extract hostname
const url = new URL('https://api.example.com/v1/users?id=123');
const hostname = url.hostname;
console.log(hostname); // "api.example.com"
For applications that process URLs from various sources, the URL() constructor is the recommended solution. It handles internationalized domain names, special characters, and complex URL structures without requiring additional processing.
const url = new URL('https://www.example.com/path/to/page');
console.log(url.hostname); // "www.example.com"
Practical Use Cases
Hostname extraction serves as the foundation for numerous web development patterns. From enterprise SaaS platforms implementing tenant isolation to marketing sites optimizing content delivery, understanding these practical applications helps you architect more robust solutions.
Multi-Tenant Application Routing
Modern SaaS platforms frequently use subdomain-based architecture to serve multiple customers from a single codebase. By extracting the subdomain from the hostname, you can route requests to the appropriate tenant's data and configuration without deploying separate applications. This pattern is a cornerstone of scalable SaaS development.
1function getTenantId(hostname) {2 const subdomain = hostname.split('.')[0];3 return subdomain !== 'www' ? subdomain : null;4}5 6const tenant = getTenantId('acme.application.com');7// Returns "acme" for tenant isolationContent Delivery and CDN Logic
Content delivery networks often serve assets from hostname-specific URLs. By detecting whether the current hostname indicates a CDN domain, applications can dynamically adjust asset paths, implement environment-specific loading strategies, or enable failover between content sources. This approach is essential for performance-optimized web applications.
1function getAssetUrl(path) {2 const hostname = window.location.hostname;3 4 if (hostname.includes('cdn.')) {5 return `https://${hostname}/${path}`;6 }7 8 // Fallback to local assets in development9 return `/assets/${path}`;10}Cross-Origin Security Checks
Validating that requests originate from trusted domains is essential for secure applications. Hostname-based validation helps prevent unauthorized access, ensures API calls come from legitimate sources, and supports proper CORS configuration for secure web applications.
1function isTrustedOrigin(currentUrl, allowedDomains) {2 const url = new URL(currentUrl);3 return allowedDomains.some(domain =>4 url.hostname === domain ||5 url.hostname.endsWith(`.${domain}`)6 );7}8 9const trusted = isTrustedOrigin(window.location.href, ['example.com']);Advanced Techniques
Manipulating Hostnames
Beyond extraction, the hostname property is fully writable, enabling programmatic URL manipulation. This capability supports scenarios like implementing domain redirects, building domain switching features, or dynamically constructing URLs based on runtime configuration.
const url = new URL('https://old.example.com/page');
url.hostname = 'new.example.com';
console.log(url.href); // "https://new.example.com/page"Browser Support
100%
Chrome Support
100%
Firefox Support
100%
Safari Support
Node 10+
Node.js Support
Summary
Hostnames are fundamental to web development, appearing in everything from simple navigation to complex multi-tenant architectures. The two primary approaches covered in this guide--location.hostname for the current page and the URL() constructor for arbitrary URLs--provide the tools you need to handle any hostname-related task.
For most use cases, starting with the URL() constructor is the best approach. It provides better error handling, supports internationalized domain names, and makes the intent of your code clear. When you specifically need information about the current page, window.location.hostname remains the most direct solution.
Building on this foundation, you can implement sophisticated routing, security, and content delivery patterns that scale with your application's needs. Whether you're developing a SaaS platform or optimizing an enterprise web application, mastering hostname handling is an essential skill for modern web developers.
Frequently Asked Questions
What's the difference between hostname and host?
The `hostname` property returns only the domain name (e.g., "example.com"), while `host` returns the hostname plus the port number if it's specified (e.g., "example.com:8080").
Can I use URL() constructor in Node.js?
Yes, the `URL` class is available in Node.js since version 10. It's part of the URL API and works the same way as in browsers.
How do I handle invalid URLs?
The `URL()` constructor throws a TypeError if the URL is invalid. Wrap your code in a try-catch block to handle invalid URLs gracefully.
Does hostname include the subdomain?
Yes, the full hostname includes any subdomains. For "api.example.com", the hostname is "api.example.com", not just "example.com".
Sources
- MDN Web Docs - Location: hostname property - Official browser API documentation
- Dmitri Pavlutin - Parse URL in JavaScript - Comprehensive URL parsing guide