🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Get Magento 2 URL in JS File

By Sanjay JethvaUpdated on May 22, 2025 1 min read

The post shows the method to get Magento 2 URL in the JS file. For example, you are stuck in a situation where you want to get url from .js file and append it with your module controller link from. Well, it is not possible to use the block to get the url.

You may require to get the URL in JS file and it is not recommended to use the static URL as with time, the URL key may change and the static value will give you the error.

Hence, implement the below method to get Magento 2 URL in JS file:

Method to Get Magento 2 URL in JS File:

define(
    [
        'jquery',
        'mage/url',
    ],
    function (jQuery,url) {
        'use strict';
        return function () {
            
            var getUrl = url.build('meetanshi/meetanshi/index');
            console.log(getUrl);
        }
    }
);

Thanks.

Sanjay Jethva Full Image
Article bySanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.