Magento 2 Get base url in js

Magento 2 Get base url in js

This tutorial is about magento 2 Get base url in js file. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how to get base url from js file in magento 2. Above all if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

So lets start our tutorial and focus on our topic. For example if you want to get base url from .js file and append it with your module controller link from. How can we do it? It is almost impossible to use block to get the base url.

Get base url

So we will look at the way how we can get base url. to do that,paste the following code in your routes.xml file


], function (url) {

  var linkUrl ='test/test/test');

Where frontname is your routes.xml file frontname.

Since it is necessary,you have to pass your frontname from routes.xml file instead of module name(namespace_module).

Furthermore you can lookup your routes.xml file from


It might work for some and might not for others.

Further more Add this code in phtml file:

<input type="hidden" value="<?php echo $this->getUrl(); ?>" id="baseUrl"/>

having done that you can use this base url in js file by id :


It is a quite useful and tested trick. So i thought to share it.

There is another approach for this task.Having said that it may too be useful.

You should pass url to js(widget).Url is a parameter of js widget.And put script below to your template where you want to.

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

Similarly in javascript widget, you can access to dataUrl by below code.

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

    return Component.extend({
        initialize: function() {

Another simple approach is

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

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

That’s it from this tutorial. I hope it serves the purpose.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.


Recent Blogs





Leave a Reply