how to get the base url in javascript

how to get the base url in javascript

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Get the Base URL in JavaScript

When building web applications, particularly those backed by server-side frameworks like CodeIgniter, you often encounter a specific friction point: dynamically switching resources from client-side code without breaking the absolute paths generated on the server. A common scenario involves defining stylesheets with PHP helper functions like base_url() to ensure they load correctly across different environments (e.g., local development vs. production). However, when you attempt to swap that resource in JavaScript—such as changing a theme based on user selection—the path often collapses to just the filename, causing a 404 error because the browser loses context about the domain and directory structure.

The naive solution presented in many legacy forums involves injecting a dummy HTML element into every page to hold the base URL string generated by PHP. While this technically works by retrieving the value via jQuery or vanilla DOM traversal, it violates clean architecture principles. It couples your JavaScript logic directly to specific HTML markup, forces you to maintain extra DOM elements that serve no other purpose, and relies on a brittle coupling between server rendering and client state management.

A more robust approach, especially within the CodeIgniter ecosystem, is to expose the base URL as a global variable directly from the server. This allows your JavaScript to operate independently of specific HTML tags while maintaining absolute path integrity. In CodeIgniter, you can achieve this by echoing a global variable into the <head> or at the top of the <body>.

// Inside your PHP view file
$page_title = 'My Page';
$this->load->helper('url');

// Generate the base URL including 'index.php' for older CI versions
$base_url = site_url(); // Or base_url('index.php') depending on config

echo "<script type=\"text/javascript\">";
echo "document.base_url = '$base_url';";
echo "</script>";

By setting document.base_url, you create a global property accessible anywhere in your JavaScript context. This eliminates the need for dummy divs or complex DOM scraping. Your subsequent logic becomes straightforward:

// Assuming the user has selected a 'dark' theme
const color = 'dark';

// Construct the new path using the absolute base URL
const newPath = document.base_url + 'assets/css/themes/' + color + '.css';

// Apply it to the existing link element
$('#style_color').attr("href", newPath);

This method is preferred because it keeps the logic centralized. If your application structure changes (e.g., moving from index.php routing to a framework-less setup), you only need to update the PHP variable assignment, not every JavaScript file or HTML template.

However, developers working in modern environments should be aware of how browsers handle this. Modern web frameworks like Laravel often prefer sending JSON responses for API routes rather than embedding variables in the view. If you are using an API-based approach, injecting a script tag that parses a JSON response is a valid alternative:

// Response from your API route (JSON)
{
    "base_url": "https://mysite.com/assets/css/themes/"
}
fetch('/api/config')
.then(response => response.json())
.then(data => {
    document.base_url = data.base_url;
});

It is important to note that document.base_url is not a standard DOM property defined by the W3C. It is a convention established by frameworks like CodeIgniter and shared with similar platforms. While this works seamlessly within those ecosystems, you must ensure that your build process or minification tools do not strip global variables if they are intended for production use. Furthermore, always sanitize any user input used to construct the final path to prevent XSS vulnerabilities, even though appending a known CSS directory usually mitigates this risk.

For those migrating from legacy PHP helpers to modern stacks, understanding how to pass this context is essential for maintaining dynamic theming capabilities without resorting to HTML clutter. If you are working on a Laravel project or similar stack, the logic remains conceptually identical, though the implementation details will differ based on your specific framework version and configuration.

Our network