Table of Contents#
- What is the Location host Property?
- Syntax
- Return Value
- Examples
- Common Use Cases
- Best Practices
- Common Pitfalls
- References
What is the Location host Property?#
The host property is a member of the Location interface, which is accessed via window.location (or simply location, since window is the global object). It returns a string representing the host of the current URL, which includes:
- The hostname (e.g.,
www.example.com,sub.domain.co). - The port number (if a non-default port is used for the protocol, e.g.,
:3000,:8080).
Crucially, host is both read-only and writable:
- When read, it returns the current host (hostname + port, if applicable).
- When set, it navigates the browser to a new URL with the specified host.
Syntax#
The syntax for accessing the host property is straightforward:
// Read the current host
const currentHost = window.location.host;
// Or simply:
const currentHost = location.host;
// Set a new host (triggers navigation)
location.host = "new-host.com:8080";Return Value#
The host property returns a string in the format:
[hostname][:port]
- Hostname: The domain name (including subdomains) of the server (e.g.,
blog.example.com). - Port: Included only if the URL uses a non-default port for its protocol. Default ports (e.g.,
80for HTTP,443for HTTPS) are omitted.
Examples#
Let’s explore practical examples to understand how host behaves in different scenarios.
Basic Usage#
Suppose the current URL is:
https://www.example.com/articles
console.log(location.host);
// Output: "www.example.com" (no port, since HTTPS uses default port 443)With a Non-Default Port#
If the URL includes a non-default port (e.g., a local development server):
http://localhost:3000/dashboard
console.log(location.host);
// Output: "localhost:3000" (port 3000 is non-default for HTTP)With a Default Port#
Default ports are omitted from host. For example:
http://example.com:80 (HTTP default port is 80)
console.log(location.host);
// Output: "example.com" (port 80 is default, so omitted)Similarly, https://example.com:443 (HTTPS default port 443) will return example.com.
Comparing host and hostname#
A common source of confusion is the difference between host and hostname. While host includes the port (if non-default), hostname only returns the domain name (no port).
Example URL: https://sub.example.com:8080/path
console.log(location.host); // "sub.example.com:8080" (hostname + port)
console.log(location.hostname); // "sub.example.com" (hostname only)| Property | Returns | Example (URL: http://blog.co:5000) |
|---|---|---|
host | Hostname + non-default port | "blog.co:5000" |
hostname | Hostname only (no port) | "blog.co" |
Common Use Cases#
The host property is versatile and useful in many scenarios:
1. Conditional Logic Based on Environment#
Developers often use host to check the current environment (e.g., development, staging, production) and apply environment-specific logic:
if (location.host === "dev.example.com") {
// Enable debug mode in development
console.log("Debug mode active");
} else if (location.host === "example.com") {
// Production-specific behavior (e.g., disable logging)
console.log = () => {};
}2. Constructing URLs Dynamically#
host can help build absolute URLs for API calls or resource loading, ensuring they point to the current server:
// Load a stylesheet from the current host
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = `https://${location.host}/styles/main.css`;
document.head.appendChild(link);3. Redirecting to a Different Host#
By setting host, you can navigate the browser to a new domain (or subdomain) with optional port:
// Redirect to a staging environment
location.host = "staging.example.com:8080";
// Navigates to http://staging.example.com:8080 (or https:// if original protocol is HTTPS)⚠️ Note: Setting host preserves the protocol (HTTP/HTTPS) of the original URL. To change the protocol, use location.protocol instead.
Best Practices#
To use host effectively, follow these best practices:
1. Use Exact Comparisons#
Always use strict equality (===) when comparing host values to avoid type coercion issues:
// Good: Strict comparison
if (location.host === "app.example.com") { ... }
// Bad: Loose comparison (may fail if types differ)
if (location.host == "app.example.com") { ... }2. Account for Default Ports#
Remember that default ports (80 for HTTP, 443 for HTTPS) are omitted from host. If your logic depends on the port, use location.port instead:
// Check if the port is 3000 (non-default)
if (location.port === "3000") {
console.log("Running on development port");
}3. Sanitize Input When Setting host#
If dynamically setting host with user input, sanitize the input to prevent navigation to malicious domains:
function safeNavigate(userInputHost) {
// Allow only whitelisted domains
const allowedHosts = ["example.com", "app.example.com"];
if (allowedHosts.includes(userInputHost)) {
location.host = userInputHost;
} else {
console.error("Invalid host");
}
}4. Avoid Relying on host for Security#
The host property reflects the current URL, which can be manipulated by attackers (e.g., via iframes with different origins). Never use host alone to authorize sensitive actions (e.g., user authentication).
Common Pitfalls#
Watch out for these common mistakes when using host:
1. Confusing host with hostname#
Forgetting that host includes the port (when non-default) while hostname does not can lead to bugs. For example:
// URL: http://example.com:8080
console.log(location.host === "example.com"); // false (host is "example.com:8080")
console.log(location.hostname === "example.com"); // true2. Assuming Port is Always Present#
Default ports (80, 443) are omitted, so code expecting a port may break:
// URL: https://example.com (default port 443)
const parts = location.host.split(":");
console.log(parts[1]); // undefined (no port in host)3. Setting host to a Relative Path#
host expects an absolute host (domain + optional port). Setting it to a relative path will fail:
// Bad: Relative path (navigates to invalid URL)
location.host = "/about";
// Good: Absolute host
location.host = "example.com/about"; // ❌ No! Host cannot include path. Use location.href instead.To navigate to a relative path, use location.href or location.pathname instead.
References#
By mastering the Location.host property, you can build more dynamic, environment-aware web applications. Remember to distinguish it from hostname, account for default ports, and sanitize inputs when modifying it. With these insights, you’ll leverage host effectively in your projects!