Table of Contents & Menu
Navigation

Building URLs in JavaScript

In Hyvä, building URLs in JavaScript is simplified by using the global window.BASE_URL variable. This replaces the need for Luma's mage/url module.

BASE_URL

Use window.BASE_URL to prepend an URL path with the current store base URL. This is equivalent to Luma's urlBuilder.build() method.

For example, to build a URL for example/path/action:

BASE_URL + "example/path/action"

Or, using a template literal:

`${BASE_URL}example/path/action`

Alternatively, you can render the base URL directly with PHP:

'<?= $escaper->escapeUrl($block->getBaseUrl()) ?>example/path/action'

Both JavaScript and PHP methods are valid; choose the one that best fits your context.

CURRENT_STORE_CODE

When your request path requires the current store code, such as for certain Ajax or REST API endpoints, use the global window.CURRENT_STORE_CODE variable.

Example using a template literal:

`${BASE_URL}/rest/${CURRENT_STORE_CODE}/example/path/action`

Or, using string concatenation:

BASE_URL + 'rest/' + CURRENT_STORE_CODE + '/example/path/action'