new URL()
Throwing Errors for Invalid URLs: A Detailed Guide
Overview
The new URL()
constructor in JavaScript is used to create a new URL object. However, if an invalid URL is provided as an argument, JavaScript throws a TypeError: Failed to construct 'URL': Invalid URL
. Understanding why this happens and how to handle such errors is crucial for robust URL handling in your applications.
1. Understanding new URL()
Constructor
The URL
constructor in JavaScript allows you to create and manipulate URLs. It is available in modern browsers and Node.js environments.
Syntax
new URL(url, [base])
url
: A string representing an absolute or relative URL.base
: (Optional) Ifurl
is a relative URL, this parameter acts as a base URL to resolve it.
Example of Correct Usage
const url = new URL("https://example.com/path?query=123");
console.log(url.hostname); // "example.com"
2. Why new URL()
Throws an Error
Common Error Message
Uncaught TypeError: Failed to construct 'URL': Invalid URL
Reasons for the Error
- Malformed URLs (e.g., missing protocols, invalid characters)
- Using relative URLs without a base
- Empty or undefined values
- Whitespace or unexpected characters in the URL
3. Examples of Errors and Fixes
❌ Example 1: Missing Protocol
const url = new URL("example.com"); // ❌ Throws "Invalid URL"
✔ Fix
Specify a protocol (http://
or https://
):
const url = new URL("https://example.com"); // ✅ No error
❌ Example 2: Relative URL Without a Base
const url = new URL("/relative/path"); // ❌ Throws "Invalid URL"
✔ Fix
Provide a base URL:
const url = new URL("/relative/path", "https://example.com"); // ✅ No error
❌ Example 3: Empty String
const url = new URL(""); // ❌ Throws "Invalid URL"
✔ Fix
Ensure the URL is non-empty:
const url = new URL("https://default.com"); // ✅ No error
❌ Example 4: Invalid Characters
const url = new URL("https://exa mple.com"); // ❌ Throws "Invalid URL"
✔ Fix
Replace spaces with %20
encoding:
const url = new URL("https://exa%20mple.com"); // ✅ No error
4. Handling Errors Gracefully
Instead of letting the application crash, use try...catch
to handle errors safely.
function safeURL(url, base) {
try {
return new URL(url, base);
} catch (error) {
console.error("Invalid URL provided:", error.message);
return null;
}
}
const validURL = safeURL("example.com"); // Logs error, returns null
const fixedURL = safeURL("https://example.com"); // Returns URL object
5. Validating URLs Before Using new URL()
To prevent errors, validate URLs before passing them into new URL()
.
Option 1: Using Regular Expressions
function isValidURL(string) {
const pattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-]*)*$/;
return pattern.test(string);
}
console.log(isValidURL("https://example.com")); // ✅ true
console.log(isValidURL("invalid-url")); // ❌ false
Option 2: Using the URL
Constructor (Try-Catch)
function isValidURL(url) {
try {
new URL(url);
return true;
} catch (_) {
return false;
}
}
console.log(isValidURL("https://example.com")); // ✅ true
console.log(isValidURL("invalid-url")); // ❌ false
6. Practical Use Cases
Example 1: Creating API Request URLs Safely
function createAPIUrl(endpoint) {
try {
return new URL(endpoint, "https://api.example.com").toString();
} catch (error) {
console.error("Invalid API URL:", error.message);
return null;
}
}
console.log(createAPIUrl("/users")); // ✅ "https://api.example.com/users"
console.log(createAPIUrl("invalid url")); // ❌ Logs error, returns null
Example 2: Redirecting Users to a Safe URL
function redirectTo(url) {
try {
const safeUrl = new URL(url);
window.location.href = safeUrl;
} catch (error) {
console.error("Invalid redirect URL:", error.message);
}
}
redirectTo("https://validsite.com"); // ✅ Redirects safely
redirectTo("invalid-url"); // ❌ Logs error
7. Summary
Issue | Cause | Solution |
---|---|---|
TypeError: Invalid URL | Missing protocol | Add http:// or https:// |
TypeError: Invalid URL | Relative URL without base | Provide a base URL |
TypeError: Invalid URL | Empty string | Use a valid URL |
TypeError: Invalid URL | Invalid characters | Encode spaces and special characters |
Preventing crashes | Unchecked user input | Use try...catch and validation |