Get base url from js file

define([
   'jquery',
   'mage/url'
], function ($,url) { 

  var linkUrl = url.build('frontname/regions/index');
  console.log(linkUrl);
});

Where frontname is your routes.xml file frontname.

You have to pass your frontname from routes.xml file instead of module name(namespace_module)

You can lookup your routes.xml file from app/code/Namespace/Module/etc/frontend/routes.xml


You can retrieve the baseUrl from the global js variable BASE_URL, and use it by setting the baseUrl from the mage/url module.

define([
   'jquery',
   'mage/url'
], function ($, url) { 
  url.setBaseUrl(BASE_URL);
  var link = url.build('foo/bar');

  console.log(link); // https://magento.com/foo/bar
});

this will return the absolute url.


I'am not sure what you are doing but i think you should pass url to js(widget).
Url is parameter of js widget
Put script below to your template where you want

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "yourWidget": {
                    "dataUrl": "<?php echo $block->getBaseUrl(); ?>"
                }
            }
        }
    }
}
</script>

In javascript widget you can access to dataUrl

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

Another approach

<script>
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
</script>

In your custom js you can easy access to window.testUrl global variable