---
title: Updating KlevuSettings
slug: klevu-magento-v4/frontend-theme-js-updating-klevusettings
docTags: 
createdAt: 2024-08-06T13:25:03.868Z
---

`KlevuSettings` is an object of data passed to the Javascript function `klevu()`. These settings determine how Klevu Theme JS is configured. Theme JS configuration documentation can be found here [https://docs.klevu.com/template-js/configuration](https://docs.klevu.com/template-js/configuration).

## How Klevu Settings is Generated

The `klevuSettings` object is generated from a combination of 2 sources.

1\) The `Klevu\Frontend\Service\KlevuSettingsBuilder` which generates an array of settings via `di.xml`, with each module injecting its own settings.
e.g.

:::CodeblockTabs
Klevu/Frontend/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="global" xsi:type="array">
                <item name="apiKey" xsi:type="object">Klevu\Frontend\Service\Provider\ApiKeyProvider</item>
                <item name="language" xsi:type="object">Klevu\Frontend\Service\Provider\LanguageProvider</item>
            </item>
        </argument>
        <argument name="isEnabledConditions" xsi:type="array">
            <item name="klevu_integrated"
                  xsi:type="object">Klevu\Frontend\Service\IsEnabledCondition\IsStoreIntegratedCondition</item>
        </argument>
    </arguments>
</type>

```
:::

2\) `Klevu\Frontend\Service\CustomSettingsBuilder` which generates data from the Custom Jsv2 Settings settings in the admin.

They are then combined with any setting from `CustomSettingsBuilder` overriding `KlevuSettingsBuilder`

***

## How KlevuSettings Is Added to head and Passed to Klevu

Klevu Jsv2 settings are added to your page `<head>` via layout xml here `module-m2-frontend/view/frontend/layout/default_head_blocks.xml`.
Specifically in block `Klevu_Frontend.js_settings` which adds 2 empty contain blocks so you can inject your own code before and after `klevu(klevuSettings)`.

The template that generates the settings is `module-m2-frontend/view/frontend/templates/html/head/js_settings.phtml`.

:::CodeblockTabs
module-m2-frontend/view/frontend/templates/html/head/js\_settings.phtml

```php
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript', 'id' => 'klevu_settings'],
    content: "\nlet klevuSettings = " . $klevuSettings . "\n",
    textContent: false,
) ?>

<?php if (!$viewModel->isSettingsGenerationError()): ?>
    <?php
    /**
     * Inject javascript into klevu_frontend.init_before
     *  to make changes to klevuSettings before passing to klevu()
     */
    ?>
    <?= $block->getChildHtml('klevu_frontend.init_before') ?>

    <?= $secureRenderer->renderTag(
        tagName: 'script',
        attributes: ['type' => 'text/javascript', 'id' => 'klevu_init'],
        content: "\nif(typeof klevuSettings !== 'undefined'){klevu(klevuSettings);}\n",
        textContent: false,
    ) ?>
    ...
```
:::

***

## Making Changes to the KlevuSettings Object

There are 3 ways to make changes to this object:

- [Set the value in the admin](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - does not change based on any business logic.
  - does not depend on any frontend element.
- [Set the value via your theme](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - is different depending on the theme (you use multiple themes in your store).
  - depends on an element on the frontend of your store that you can access via javascript.
- [Set the value via a custom module](https://docs.klevu.com/apis/smart-search-analytics-events#Ai6mR).&#x20;
  Use this if the value:
  - depends on values stored in your database.
  - depends on more complex business logic.
  - depends on an element on the frontend of your store that you can access via javascript, you have multiple themes on your site and you need to apply the change to them all.

In reality you will likely use a combination of all 3, some set in the admin, some set in theme  or module templates that may use a ViewModel defined in your customer module.

### Adding Klevu Theme Settings Via Admin

***JSv2 settings NOT found in Stores > Configuration > Klevu Section***

Magento already has a setting for these, so we’re using the existing settings rather than duplicating them and causing potential confusion.

- Minimum characters used in search, `Stores > Configuration > Catalog > Catalog > Search > Minimal Query Length`
- Maximum characters used in search, `Stores > Configuration > Catalog > Catalog > Search > Maximum Query Length`
- Language, `Stores > Configuration > General > Locale Options > Locale`

***JSv2 settings in Stores > Configuration > Klevu Section***

**All JSv2 settings in config can be overwritten by using&#x20;**`Stores > Configuration > Klevu > Developer Settings > Frontend > Custom JSv2 Settings`**.**
e.g. if you need to defer the powerUp of the SRLP you can do that here. Set path = powerUp.landing, type=boolean, value=false.

A list of available settings can be found here [https://docs.klevu.com/template-js/configuration](https://docs.klevu.com/template-js/configuration)

![](https://api.archbee.com/api/optimize/816_4eGYZQxALlijMlcBN/fw5Yvq2nsjQFKABSF8LrN_screenshot-2023-08-14-at-092507.png "Custom JSv2 Settings")

There are 2 settings we have given their own fields within `Stores > Configuration > Klevu > Developer Settings > Frontend`. They are

- Search Box Selector: The id, class, or handle used to bind the search input field. This is equivalent to setting `search.searchBoxSelector` in Custom Jsv2 Options.
- Search Query Parameter: The query parameter appended to the SRLP URL. This is equivalent to setting `url.queryParam` in Custom Jsv2 Options.

:::hint{type="info"}
Note: Any values set in Custom JSv2 Settings will override values set in `di.xml`
:::

:::hint{type="info"}
After changing any configuration settings, please remember to clear the Config cache.
:::

***

### Adding Klevu Theme Settings Via Theme

[Magento theme structure documentation](https://developer.adobe.com/commerce/frontend-core/guide/themes/structure/).

Sometimes setting these values via the admin is not an option.
You may need to:

- use Javascript to get an element from the page
- have different settings for different themes within the same store.

**Change KlevuSettings Before They are Passed to klevu()**

1. In your theme create a module Klevu\_Frontend, `app/code/design/frontend/Vendor/theme/Klevu_Frontend`
2. Create a layout file to add your blocks to our contain `klevu_frontend.init_before`
   `app/code/design/frontend/Vendor/theme/Klevu_Frontend/layout/default_head_blocks.xml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/layout/default\_head\_blocks.xml

```xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="klevu_frontend.init_before">
            <block name="Vendor_Theme.klevu.init_before"
                   template="Klevu_Frontend::klevu/init_before.phtml"
                   before="-"/>
        </referenceContainer>
    </body>
</page>
```
:::

3\. Create the template file that will contain your customisations
`app/code/design/frontend/Vendor/theme/Klevu_Frontend/templates/klevu/init_before.phtml`

:::CodeblockTabs
app/code/design/frontend/Vendor/theme/Klevu\_Frontend/templates/klevu/init\_before.phtml

```php
<?php

use Magento\Framework\View\Helper\SecureHtmlRenderer;

/**
 * @var SecureHtmlRenderer $secureRenderer
 */

/** add your customisation e.g */
$scriptString = "
    klevu.setObjectPath(
        klevuSettings, // the object of settings we wish to amend
        'search.showQuickOnEnter', // the path in the object we wish to add/amend
        klevu.toBoolean(true) // the value to set
    );
";
?>

<?php /** Render the script tag */ ?>
<?= $secureRenderer->renderTag(
    tagName: 'script',
    attributes: ['type' => 'text/javascript'],
    content: $scriptString,
    textContent: false
) ?>

```
:::

***

### Adding Klevu Theme Settings Via A Custom Module

Note the example below we have used Module Vendor\_Module.
[Magento module creation documentation](https://experienceleague.adobe.com/en/docs/commerce-learn/tutorials/backend-development/create-module).

To add a new setting to `klevuSettings` before the object is output to the page you can add to the `KlevuSettingsBuilder` via frontend `di.xml`.
It is possible to set `boolean`, `const`, `number` and `string` in the XML, though these can also be set in the admin.

:::hint{type="warning"}
Note: Any values set in [Custom JSv2 Settings](https://docs.klevu.com/klevu-magento-v4/updating-klevusettings#sX4hi) will override values set here via `di.xml`
:::

`Vendor/Module/etc/di.xml`

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="search" xsi:type="array">
                <item name="searchBoxTarget" xsi:type="boolean">true</item>
                <item name="maxChars" xsi:type="number">5</item>
                <item name="documentClickPreventSelector" xsi:type="string">#someId</item>
            </item>
            <item name="url" xsi:type="array">
                <item name="queryParam" xsi:type="string">queryParam</item>
            </item>
        </argument>
    </arguments>
</type>
```
:::

`<argument name="klevuSettings" xsi:type="array">` contains all the data output as `klevuSettings`.
The names of the items make up the paths in `klevuSettings`.
The generated output of the above XML would be

```javascript
klevuSettings = {
    search: {
        searchBoxTarget: true,
        maxChars: 5,
        documentClickPreventSelector: "#someId"
    },
    url : {
        queryParam: "queryParam"
    }
};
```

More interesting though is the ability to pass an instance of `Klevu\FrontendApi\Service\Provider\SettingsProviderInterface`
e.g.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<type name="Klevu\Frontend\Service\KlevuSettingsBuilder">
    <arguments>
        <argument name="klevuSettings" xsi:type="array">
            <item name="search" xsi:type="array">
                <item name="searchBoxSelector" xsi:type="object">Vendor\Module\Service\Provider\YourProvider</item>
            </item>
        </argument>
    </arguments>
</type>
```
:::

If the provider returns a value from `core_config_data` you can create a `virtualType` for `Klevu\Frontend\Service\Provider\SettingsProvider` and pass it the path and return type.

:::CodeblockTabs
Vendor/Module/etc/di.xml

```xml
<virtualType name="Vendor\Module\Service\Provider\YourProvider"
    type="Klevu\Frontend\Service\Provider\SettingsProvider">
    <arguments>
        <argument name="path" xsi:type="string">path/to_your/setting</argument>
        <argument name="returnType"
                  xsi:type="const">Klevu\Frontend\Block\Adminhtml\Form\Field\TypeColumn::TYPE_VALUE_STRING</argument>
    </arguments>
</virtualType>
```
:::

Valid `returnType` are `TYPE_VALUE_BOOLEAN`, `TYPE_VALUE_INTEGER`, and `TYPE_VALUE_STRING`.

If your provider requires more business logic, create the class that implements `Klevu\FrontendApi\Service\Provider\SettingsProviderInterface`.

:::CodeblockTabs
Vendor/Module/Service/Provider/YourProvider.php

```php
<?php

declare(strict_types=1);

namespace Vendor\Module\Service\Provider;

use Klevu\FrontendApi\Service\Provider\SettingsProviderInterface;

class YourProvider implements SettingsProviderInterface
{
    public function get(): string|int|bool|null
    {
        // add your logic
    }
}
```
:::

Settings Provider Examples

- `Klevu\Frontend\Service\Provider\ApiKeyProvider`
- `Klevu\FrontendSearch\Service\Provider\LandingUrlProvider`
- `Klevu\FrontendCategoryNavigation\Service\Provider\LandingInfiniteScrollOffsetProvider`

:::hint{type="info"}
Your provider may throw an exception of type `Klevu\Frontend\Exception\OutputDisabledException`.
This will prevent the setting from being added to the output.
:::



