import { MdxImage } from "@/components/mdx-image";

import I1 from "./images/1-set-up-in-app-micro-survey-popup.webp";
import I2 from "./images/2-micro-survey-pop-up-in-app.webp";
import I3 from "./images/3-survey-logs-in-app-survey-popup.webp";

export const metadata = {
  title: "Formbricks JS SDK",
  description:
    "Integrate Formbricks App Surveys into your web apps and websites with the Formbricks JS SDK. Learn how to initialize Formbricks, set attributes, track actions, and troubleshoot common issues.",
};

#### Developer Docs

# SDK: Run Surveys Inside Your Web Apps and Websites

### Overview

The Formbricks JS SDK is a versatile solution for integrating surveys into both web apps and websites. It adapts based on the presence of a `userId`. If a `userId` is provided, the SDK handles authenticated surveys for logged-in users in web apps. If no `userId` is provided, the SDK can still seamlessly run surveys on public-facing websites. The SDK is available on npm [here](https://www.npmjs.com/package/@formbricks/js/).

### Install

<Col>
<CodeGroup title="npm">

```js {{ title: 'npm' }}
npm install @formbricks/js
```

```js {{ title: 'yarn' }}
yarn add @formbricks/js
```

```js {{ title: 'pnpm' }}
pnpm add @formbricks/js
```

</CodeGroup>
</Col>

## Methods

### Initialize Formbricks

Initialize the Formbricks JS Client for surveys. When used in a web app, pass a `userId` to create and target a specific user. When using it on a website without authentication, simply omit the `userId`.

<Col>
<CodeGroup title="Initialize Formbricks">

```javascript
import formbricks from "@formbricks/js";

formbricks.init({
  environmentId: "<your-environment-id>", // required
  apiHost: "<your-api-host>", // required
  userId: "<user-id>", // optional
});
```

</CodeGroup>
</Col>

The moment you initialise Formbricks, your user will start seeing surveys that get triggered on simpler actions such as on New Session, Page Exit, & other custom actions!

<Note>
Formbricks JS is a client SDK meant to be run client-side in their browser so make sure the window object is accessible. Below is an example of how you can set it!

<Col>
<CodeGroup>

```js
if (window !== undefined) {
  formbricks.init({
    environmentId: "<your-environment-id>",
    apiHost: "<your-api-host>",
    userId: "<user-id>", //optional
  });
} else {
  console.error("Window object not accessible to init Formbricks");
}
```

</CodeGroup>
</Col>

</Note>

### Set Attribute

Set custom attributes for the identified user to help segment them based on specific characteristics. This method only works when a `userId` is provided during initialization, allowing for targeted surveys in web apps. To learn how to set custom user attributes, refer to our [User Attributes Guide](/app-surveys/user-identification).

<Col>
<CodeGroup>

```js
formbricks.setAttribute("Plan", "Paid");
```

</CodeGroup>
</Col>

### Track Action

Track user actions to trigger surveys based on user interactions, such as button clicks or scrolling:

<Col>
<CodeGroup>

```js
formbricks.track("Clicked on Claim");
```

</CodeGroup>
</Col>

### Logout

To log out and deinitialize Formbricks, use the formbricks.logout() function. This action clears the current initialization configuration and erases stored frontend information, such as the surveys a user has viewed or completed. It's an important step when a user logs out of your application or when you want to reset Formbricks.

<Col>
<CodeGroup>

```js
formbricks.logout();
```

</CodeGroup>
</Col>

After calling formbricks.logout(), you'll need to reinitialize Formbricks before using any of its features again. Ensure that you properly reinitialize Formbricks to avoid unexpected errors or behavior in your application.

### Reset

Reset the current instance and fetch the latest surveys and state again:

<Col>
<CodeGroup>

```js
formbricks.reset();
```

</CodeGroup>
</Col>

### Register Route Change:

Listen for page changes and dynamically show surveys configured via no-code actions in the Formbricks app:

<Note>
  This is only needed when your framework has a custom routing system and you want to trigger surveys on route changes. For example: NextJs
</Note>

<Col>
<CodeGroup>

```js
formbricks.registerRouteChange();
```

</CodeGroup>
</Col>

## Debug Mode

To enable debug mode in Formbricks, add `?formbricksDebug=true` to your app’s URL.

For example, if you’ve integrated Formbricks JS to your app hosted at `https://example.com`, then change the URL to `https://example.com?formbricksDebug=true` and refresh the page, now view the console logs to see the debug mode live in action.

This activates detailed debug messages in the browser console, providing deeper insights into Formbricks' operation and potential issues.

---

## Troubleshooting

In case you don’t see your survey right away, here's what you can do. Go through these to find the error fast:

### Formbricks Cloud and your app are not connected properly.

Go back to [app.formbricks.com](http://app.formbricks.com) or your self-hosted instance's URL and go to the App connection in the Configuration. If the status is still indicated as “Not connected” your app hasn't yet pinged the Formbricks Cloud:

<MdxImage
  src={I1}
  alt="setup checklist ui of survey popup for app surveys"
  quality="100"
  className="max-w-full rounded-lg sm:max-w-3xl"
/>
**How to fix it:**

1. Check if your app loads the Formbricks widget correctly.
2. Make sure you have `debug` mode enabled in your integration and you should see the Formbricks debug logs in your browser console while being in your app (right click in the browser, `Inspect`, switch to the console tab). If you don’t see them, double check your integration.

---

### Survey not loaded

If your app is connected with Formbricks Cloud, the survey might have not been loaded properly. Check the debug logs and search for the list of surveys loaded. It should look like so:

<MdxImage
  src={I3}
  alt="survey logs for app survey pop up micro"
  quality="100"
  className="max-w-full rounded-lg sm:max-w-3xl"
/>

**How to fix it:**

The widget only loads surveys which are **public** and **in progress**. Go to Formbricks Cloud and to the Survey Summary page. Check if your survey is live:

<MdxImage
  src={I2}
  alt="ui of survey popup for app micro surveys"
  quality="100"
  className="max-w-full rounded-lg sm:max-w-3xl"
/>

---

### Survey not triggered

If the survey is loaded by the widget it might not have been triggered properly.

**How to fix:**

1. Open your local app in an incognito tab or window. The New Session event is only fired if a user was inactive for 60 minutes or was logged out of Formbricks via formrbicks.logout().
2. Check the debug logs for “Event ‘New Session” tracked”. If you see it in the logs and the survey still did not get displayed, [please let us know.](mailto:support@formbricks.com)

---

### Survey not displayed in HTML page

If the survey is loaded by the widget in the HTML page, try the below steps:

**How to fix:**

1. Make sure you have added the [script](/app-surveys/framework-guides#html) in the head of the HTML page.
2. Verify that you have set the \<environment-id\> and \<host\> as per your Formbricks instance.
3. Verify that you have the latest version of the JS Package.
4. Check the debug logs to see if you still see any errors.

---

### Cannot read undefined of .init()

If you see this error in the console, it means that the Formbricks JS package is not loaded properly.

**How to fix:**

1. Update to the latest version of the JS Package.
2. Verify this wherever you call initialise the Formbricks instance in your code.
3. It should now start working.

---

If you have any questions or need help, feel free to reach out to us on **[Github Discussions](https://github.com/formbricks/formbricks/discussions)**
