DEV Community

Cover image for ๐Ÿ”„ Replacing the Base URL of a Path in JavaScript
Amit Kumar
Amit Kumar

Posted on

1 1 1 1 1

๐Ÿ”„ Replacing the Base URL of a Path in JavaScript

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;
  }
};

Enter fullscreen mode Exit fullscreen mode

๐Ÿ” 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'

Enter fullscreen mode Exit fullscreen mode

โš ๏ธ 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!

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.devโ€™s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one serverโ€”search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. โค๏ธ