In modern web or mobile development, working with dynamic URLs is common โ especially when environments (development, staging, production) have different base URLs but share similar API paths. One useful helper function is replacing just the base URL of an existing URL string while preserving its path and query parameters.
Hereโs a handy utility function to do just that:
export const replaceBaseUrl = (oldUrl, newUrl) => {
try {
const parser = new URL(oldUrl); // Parse the original URL
const newUrlObject = new URL(parser?.pathname, newUrl); // Replace the base URL while keeping the path
return newUrlObject?.toString(); // Return the updated URL as a string
} catch (error) {
// You can log or handle errors here
console.error("Invalid URL:", error);
return null;
}
};
๐ How It Works
-
new URL(oldUrl)
is used to safely parse the existing URL. -
parser.pathname
extracts just the path portion (e.g.,/api/user/123
). -
new URL(pathname, newUrl)
creates a new URL with the same path but a new base. - The result is returned as a string using
toString().
โ Example Usage
const oldUrl = 'https://old-api.example.com/api/user/123';
const newBase = 'https://new-api.example.com';
const updatedUrl = replaceBaseUrl(oldUrl, newBase);
console.log(updatedUrl);
// Output: 'https://new-api.example.com/api/user/123'
โ ๏ธ Error Handling
If an invalid URL is passed, the function catches the error and logs it, returning null
.
You can customize the error handling section to suit your needs, such as throwing the error, logging it to a monitoring service, or returning a fallback URL.
๐ฏ When to Use This
- Switching environments dynamically (Dev, QA, Prod)
- Migrating to a new domain without changing path structures
- Proxying requests in mobile apps
- Rewriting URLs for API redirection
Final Thoughts
The replaceBaseUrl function is a small but powerful utility that can simplify how you manage endpoint configurations across multiple environments. Clean, readable, and practical โ exactly how utility functions should be.
Let me know if youโd like to expand this into a code snippet component or integrate it with a URL manager service!
Top comments (0)