> For the complete documentation index, see [llms.txt](https://docs.hackle.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hackle.io/en/development-guide/javascript.md).

# JavaScript

{% hint style="info" %}
The JavaScript SDK supports IE11+ and all major browsers.

To use the JavaScript SDK, `Promise` and `Map` APIs must be supported. If polyfills are needed, we recommend using `core-js`.
{% endhint %}

{% hint style="success" %}
Framework Support

* You can use the JavaScript SDK with Angular, Vue, or other frameworks.
* If you are using React, refer to the [React](/en/development-guide/react.md) guide.
* If you are using Next.JS, refer to the [Next.js](/en/development-guide/nextjs-index.md) guide.
* For integration via Google Tag Manager, see the [GTM documentation](/en/development-guide/google-tag-manager.md).

If you need support for a specific environment or framework, please contact us via [Hackle Slack Community](https://join.slack.com/t/hackle-community/shared_invite/zt-1awrnygsh-U8VCHwN06ZDTF9yAzik5SA) or <support@hackle.io>.
{% endhint %}

## Add Dependency

[![](https://img.shields.io/npm/v/%40hackler%2Fjavascript-sdk)](https://www.npmjs.com/package/@hackler/javascript-sdk)

{% tabs %}
{% tab title="NPM" %}

```shell
npm install --save @hackler/javascript-sdk
```

{% endtab %}

{% tab title="YARN" %}

```shell
yarn add @hackler/javascript-sdk
```

{% endtab %}

{% tab title="HTML" %}

```html
<!-- HTML의 경우 의존성 추가 작업이 필요하지 않습니다 -->
```

{% endtab %}
{% endtabs %}

## SDK Initialization

You must initialize `HackleClient` before using the SDK.

* `HackleClient` is the class that provides methods for using SDK features.
* You can find the SDK Key in [SDK Integration Info](https://dashboard.hackle.io/config/sdk-setting) on the Hackle Dashboard.

{% tabs %}
{% tab title="JavaScript" %}

```javascript
import * as Hackle from "@hackler/javascript-sdk";

// YOUR_BROWSER_SDK_KEY로 초기화
const hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY");
```

{% endtab %}

{% tab title="HTML" %}

```html
<!-- 기존 코드 head 안에 추가 -->
<script src="https://cdn2.hackle.io/npm/@hackler/javascript-sdk@11.52.0/lib/index.browser.umd.min.js"></script>
<script>
  // YOUR_BROWSER_SDK_KEY로 초기화
  window.hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY");
</script>
```

{% endtab %}
{% endtabs %}

### Initialization Complete

Initialization runs **asynchronously** and fetches necessary data from the Hackle server and stores it in the SDK.\
You can use `await` to wait until initialization is complete.

{% hint style="warning" %}
**Do not call SDK features before initialization is complete.**

Initialization runs asynchronously and is only complete once synchronization with the Hackle server has finished. If you call SDK features before initialization is complete, the SDK may not work correctly or events may be lost.

* **A/B Tests, Feature Flags, and Remote Config do not work correctly.** Instead of the actual assignment result, they return the default group (`A`), off (`false`), or the default value passed in the call. (Reason: `SDK_NOT_READY`)
* **Exposure events are not recorded.** Even if a user was actually part of the experiment, they are not counted as exposed, which can distort the experiment results.
* **Events may be lost.** Events collected with `track()` may not be sent.
* **Events may carry an inaccurate session ID.**
* **In-App Messages are not displayed.** Trigger conditions are evaluated at the moment an event is collected, and events collected before initialization is complete are not re-evaluated afterwards.

Make sure to call SDK features only after initialization is complete.
{% endhint %}

If you await `onInitialized()`, you can use the SDK after initialization is complete. Even if initialization fails due to a network error or similar issue, subsequent SDK calls safely return the default values.

```javascript
async function initHackle(){
  try {
    await hackleClient.onInitialized();
    // SDK ready to use
  } catch (e) {
    // Even if initialization fails, subsequent SDK calls return the default values (A, false).
    console.warn("Hackle initialization failed:", e);
  }
}

initHackle();
```

```javascript
// deprecated: onReady is deprecated because it does not support the Promise-based async/await pattern.
// Please use onInitialized() instead.
hackleClient.onReady(() => {
    // SDK ready to use
});
```

### SDK Initialization Config

You can initialize the SDK with configuration options.

```javascript
const config = {
  debug: true
};

const hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY", config);
```

#### Configuration Options

<table data-full-width="false"><thead><tr><th width="213.57421875">Option</th><th width="295.48828125">Description</th><th width="125.8125">Default</th><th width="108.09765625">Supported Version</th></tr></thead><tbody><tr><td><code>debug</code></td><td>Prints logs for all features to the console.</td><td><code>false</code></td><td>1.0.0+</td></tr><tr><td><code>pollingIntervalMillis</code></td><td><p>Periodically updates the configuration set in the Dashboard.</p><ul><li>Minimum: 60000 (60 seconds)</li></ul></td><td>-1<br>(no periodic update)</td><td>11.1.0+</td></tr><tr><td><code>exposureEventDedupIntervalMillis</code></td><td><p>Removes duplicate exposure events for the same A/B Test or Feature Flag distribution result triggered by the same user consecutively.</p><ul><li>Minimum: 1000 (1 second)</li><li>Maximum: 3600000 (1 hour)</li></ul></td><td>60000 (1 min / 11.23.0+)<br>-1 (no dedup / below 11.23.0)</td><td>11.1.0+</td></tr><tr><td><code>devTool</code></td><td>Enables <a href="/en/development-guide/javascript/js-user-explorer.md">User Explorer</a>.</td><td><code>undefined</code></td><td>11.13.0+</td></tr><tr><td><code>autoOpenDevTool</code></td><td>Option to automatically show the User Explorer button.</td><td><code>false</code></td><td>11.13.0+</td></tr><tr><td><code>sameSiteCookie</code></td><td>Sets the sameSite flag on Hackle cookies and determines cookie privacy policy.</td><td><code>Lax</code></td><td>11.20.0+</td></tr><tr><td><code>secureCookie</code></td><td>When set to <code>true</code>, sets the Secure flag on Hackle cookies.</td><td><code>false</code></td><td>11.20.0+</td></tr><tr><td><code>user</code></td><td>Injects a user at initialization time.</td><td><code>undefined</code></td><td>11.22.3+</td></tr><tr><td><code>sessionPolicy</code></td><td>Configures session persistence and expiration conditions.</td><td><p><code>ALWAYS_NEW_SESSION</code> ,</p><p><code>1800000</code></p></td><td>11.54.0+</td></tr><tr><td><code>optOutTracking</code></td><td>Whether opt-out is enabled.</td><td><code>false</code></td><td>11.54.0+</td></tr><tr><td><code>evaluationMode</code></td><td>Configures the evaluation mode.</td><td><code>local</code></td><td>12.0.0+</td></tr><tr><td><code>sessionTimeoutMillis</code><br>(deprecated)</td><td>Sets the session expiration time. Please use <code>sessionPolicy</code> instead.</td><td>1800000 (30 min)</td><td>11.8.0+</td></tr></tbody></table>

#### Evaluation Mode Configuration

You can choose whether the SDK performs evaluation itself or fetches results that the Hackle server has already evaluated.\
If not configured, the default value `"local"` (local evaluation) is used.

```javascript
const config = {
    evaluationMode: "remote"
};

const hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY", config);
```

{% hint style="warning" %}
When you use remote evaluation, user information is not stored in the browser. If user information was already stored while using local evaluation, it is deleted.

For the differences between the two modes and how to choose between them, refer to the [Evaluation Mode](/en/development-guide/sdk/evaluation-mode.md) documentation.
{% endhint %}

#### Session Policy Configuration

You can configure session persistence and expiration conditions using the session policy.

```javascript
const config = {
    sessionPolicy: {
        timeoutMillis: 3600000,
        persistCondition: HackleSessionPersistConditions.NULL_TO_USER_ID
    }
};

const hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY", config);
```

#### Injecting User at Initialization

When `user` is set in config, you can initialize the SDK with user information included.

* If no user information is provided, the user information stored in cookies is used.
* If user information is provided, the user information stored in cookies is not used.
* If there is no user information in cookies, a user with the Hackle Device ID as the device id is used.

{% hint style="info" %}
You can freely update user information after SDK initialization using the user information setter functions.
{% endhint %}

{% hint style="warning" %}
The user information injected at initialization and the user information stored in cookies are not merged.

e.g.) If `userId: A` is stored in cookies and you inject `deviceId: B` at initialization, the user is set to `userId: null, deviceId: B`.
{% endhint %}

```javascript
const user = {
  userId: "LOGIN_ID",
  deviceId: "CUSTOM_DEVICE_ID"
};

const config = {
  user: user
};

const hackleClient = Hackle.createInstance("YOUR_BROWSER_SDK_KEY", config);
```

### Refreshing Dashboard Configuration

You can explicitly refresh the Dashboard configuration.

{% hint style="warning" %}
This function can only be called once every 60 seconds.
{% endhint %}

```javascript
await hackleClient.fetch();
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.hackle.io/en/development-guide/javascript.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
