import { MdxImage } from "@/components/MdxImage";

import { Libraries } from "./components/Libraries";

import ReactApp from "./images/react-in-app-survey-app-popup-form.webp";
import WidgetConnected from "./images/widget-connected.webp";
import WidgetNotConnected from "./images/widget-not-connected.webp";

export const metadata = {
  title: "Integrate Formbricks: Comprehensive Framework Guide & Integration Tutorial",
  description:
    "Master the integration of Formbricks into your application with our detailed guides. From HTML to ReactJS, NextJS, and VueJS, get step-by-step instructions and ensure seamless setup.",
};

# Framework Guides

One can integrate Formbricks App Survey SDK into their app using multiple options! Checkout the options below that we provide! If you are looking
for something else, please [join our Discord!](https://formbricks.com/discord) and we would be glad to help.

<Libraries />

---

## Prerequisites

Before getting started, make sure you have:

1. A web application (behind your user authentication system) in your desired framework is set up and running.
2. A Formbricks account with access to your environment ID and API host. You can find these in the **Setup Checklist** in the Settings.

---

## HTML

All you need to do is copy a `<script>` tag to your HTML head, and that’s about it!

<Col>
<CodeGroup title="HTML">
```html {{ title: 'index.html' }}
<!-- START Formbricks Surveys -->
<script type="text/javascript">
!function(){
    var apiHost = "https://app.formbricks.com";
    var environmentId = "<your-environment-id>";
    var userId = "<your-user-id>";
    var t=document.createElement("script");t.type="text/javascript",t.async=!0,t.src=apiHost+"/api/packages/app";var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e),setTimeout(function(){window.formbricks.init({environmentId: environmentId, apiHost: apiHost, userId: userId})},500)}();
</script>
<!-- END Formbricks Surveys -->
```
</CodeGroup>
</Col>
### Required customizations to be made

<Properties>
  <Property name="environment-id" type="string">
    Formbricks Environment ID.
  </Property>
  <Property name="api-host" type="string">
    URL of the hosted Formbricks instance.
  </Property>
  <Property name="userId" type="string">
    User ID of the user who has active session.
  </Property>
</Properties>

Refer to our [Example HTML project](https://github.com/formbricks/examples/tree/main/html) for more help! Now visit the [Validate your Setup](#validate-your-setup) section to verify your setup!

---

## ReactJS

Install the Formbricks SDK using one of the package managers ie `npm`,`pnpm`,`yarn`. Note that zod is required as a peer dependency must also be installed in your project.

<Col>
<CodeGroup title="Install Formbricks JS library">
```shell {{ title: 'npm' }}
npm install @formbricks/js zod
```
```shell {{ title: 'pnpm' }}
pnpm add @formbricks/js zod
```
```shell {{ title: 'yarn' }}
yarn add @formbricks/js zod
```

</CodeGroup>
</Col>
Now, update your App.js/ts file to initialise Formbricks.
<Col>
<CodeGroup title="src/App.js">

```js
// other imports
import formbricks from "@formbricks/js/app";

if (typeof window !== "undefined") {
  formbricks.init({
    environmentId: "<environment-id>",
    apiHost: "<api-host>",
    userId: "<user-id>",
  });
}

function App() {
  // your own app
}

export default App;
```

</CodeGroup>
</Col>
### Required customizations to be made

<Properties>
  <Property name="environment-id" type="string">
    Formbricks Environment ID.
  </Property>
  <Property name="api-host" type="string">
    URL of the hosted Formbricks instance.
  </Property>
  <Property name="userId" type="string">
    User ID of the user who has active session.
  </Property>
</Properties>

Refer to our [Example ReactJs project](https://github.com/formbricks/examples/tree/main/reactjs) for more help! Now visit the [Validate your Setup](#validate-your-setup) section to verify your setup!

---

## NextJS

NextJs projects typically follow two main conventions: the App Directory and the Pages Directory.
To ensure smooth integration with the Formbricks SDK, which operates solely on the client side, follow the
guidelines for each convention below:

- App directory: You will have to define a new component in `app/formbricks.tsx` file and call it in your `app/layout.tsx` file.
- Pages directory: You will have to visit your `_app.tsx` and just initialise Formbricks there.

Code snippets for the integration for both conventions are provided to further assist you.

<Col>
<CodeGroup title="Install Formbricks JS library">
```shell {{ title: 'npm' }}
npm install @formbricks/js zod
```
```shell {{ title: 'pnpm' }}
pnpm add @formbricks/js zod
```
```shell {{ title: 'yarn' }}
yarn add @formbricks/js zod
```

</CodeGroup>
</Col>

### App Directory

<Col>
<CodeGroup title="app/formbricks.tsx">

```tsx {{title: 'Typescript'}}
"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import formbricks from "@formbricks/js/app";

export default function FormbricksProvider() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    formbricks.init({
      environmentId: "<environment-id>",
      apiHost: "<api-host>",
      userId: "<user-id>",
    });
  }, []);

  useEffect(() => {
    formbricks?.registerRouteChange();
  }, [pathname, searchParams]);

  return null;
}
```

</CodeGroup>

<CodeGroup title="app/layout.tsx">
```tsx {{title: 'Typescript'}}
// other imports
import FormbricksProvider from "./formbricks";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <FormbricksProvider />
      <body>{children}</body>
    </html>
  );
}
```

</CodeGroup>
</Col>

Refer to our [Example NextJS App Directory project](https://github.com/formbricks/examples/tree/main/nextjs-app) for more help!

### Pages Directory

<Col>
<CodeGroup title="src/pages/_app.tsx">

```tsx {{ title: 'Typescript' }}
// other import
import { useRouter } from "next/router";
import { useEffect } from "react";
import formbricks from "@formbricks/js/app";

if (typeof window !== "undefined") {
  formbricks.init({
    environmentId: "<environment-id>",
    apiHost: "<api-host>",
    userId: "<user-id>",
  });
}

export default function App({ Component, pageProps }: AppProps) {
  const router = useRouter();

  useEffect(() => {
    // Connect next.js router to Formbricks
    const handleRouteChange = formbricks?.registerRouteChange;
    router.events.on("routeChangeComplete", handleRouteChange);

    return () => {
      router.events.off("routeChangeComplete", handleRouteChange);
    };
  }, []);
  return <Component {...pageProps} />;
}
```

</CodeGroup>
</Col>
Refer to our [Example NextJS Pages Directory project](https://github.com/formbricks/examples/tree/main/nextjs-pages) for more help!

### Required customizations to be made

<Properties>
  <Property name="environment-id" type="string">
    Formbricks Environment ID.
  </Property>
  <Property name="api-host" type="string">
    URL of the hosted Formbricks instance.
  </Property>
  <Property name="userId" type="string">
    User ID of the user who has active session.
  </Property>
</Properties>

First we initialize the Formbricks SDK, ensuring that it only runs on the client side.
To connect the Next.js router to Formbricks and ensure the SDK can keep track of every page change, we are registering the route change event.

Now visit the [Validate your Setup](#validate-your-setup) section to verify your setup!

---

## VueJs

Integrating the Formbricks SDK with Vue.js is a straightforward process.
We will make sure the SDK is only loaded and used on the client side, as it's not intended for server-side usage.

<Col>
<CodeGroup title="Install Formbricks JS library">
```shell {{ title: 'npm' }}
npm install @formbricks/js
````

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

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

</CodeGroup>

<CodeGroup title="src/formbricks.js">

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

if (typeof window !== "undefined") {
  formbricks.init({
    environmentId: "<environment-id>",
    apiHost: "<api-host>",
    userId: "<user-id>",
  });
}

export default formbricks;
```

</CodeGroup>

<CodeGroup title="src/main.js">

```js
// other imports
import formbricks from "@/formbricks";

const app = createApp(App);

app.use(router);

app.mount("#app");

router.afterEach((to, from) => {
  if (typeof formbricks !== "undefined") {
    formbricks.registerRouteChange();
  }
});
```

</CodeGroup>
</Col>
### Required customizations to be made

<Properties>
  <Property name="environment-id" type="string">
    Formbricks Environment ID.
  </Property>
</Properties>
<Properties>
  <Property name="api-host" type="string">
    URL of the hosted Formbricks instance.
  </Property>
  <Property name="userId" type="string">
    User ID of the user who has active session.
  </Property>
</Properties>

Refer to our [Example VueJs project](https://github.com/formbricks/examples/tree/main/vuejs) for more help! Now visit the [Validate your Setup](#validate-your-setup) section to verify your setup!

## Validate your setup

Once you have completed the steps above, you can validate your setup by checking the **Setup Checklist** in the Settings. Your widget status indicator should go from this:

<MdxImage
  src={WidgetNotConnected}
  alt="Widget isnt connected"
  quality="100"
  className="max-w-full rounded-lg sm:max-w-3xl"
/>

To this:

<MdxImage
  src={WidgetConnected}
  alt="Widget is connected"
  quality="100"
  className="max-w-full rounded-lg sm:max-w-3xl"
/>

## Debugging Formbricks Integration

Enabling Formbricks debug mode in your browser is a useful troubleshooting step for identifying and resolving complex issues. This section outlines how to activate debug mode, covers common use cases, and provides insights into specific debug log messages.

### Activate Debug Mode

To activate Formbricks debug mode:

1. **Via URL Parameter:**

   - Enable debug mode mode by adding `?formbricksDebug=true` to your application's URL (e.g. `https://example.com?formbricksDebug=true` or `https://example.com?page=123&formbricksDebug=true`). This parameter will enable debugging for the current page.

2. **View Debug Logs:**

   - Open your browser's developer tools by pressing `F12` or right-clicking and selecting "Inspect."
   - Navigate to the "Console" tab to view Formbricks debugging information.

     **How to Open Browser Console:**

     - **Google Chrome:** Press `F12` or right-click, select "Inspect," and go to the "Console" tab.
     - **Firefox:** Press `F12` or right-click, select "Inspect Element," and go to the "Console" tab.
     - **Safari:** Press `Option + Command + C` to open the developer tools and navigate to the "Console" tab.
     - **Edge:** Press `F12` or right-click, select "Inspect Element," and go to the "Console" tab.

### Common Use Cases

Debug mode is beneficial for scenarios such as:

- Verifying Formbricks initialization.
- Identifying survey trigger issues.
- Troubleshooting unexpected behavior.

### Debug Log Messages

Debug log messages provide insights into:

- API calls and responses.
- Event tracking, survey triggers and form interactions.
- Initialization errors.

**Can’t figure it out? [Join our Discord!](https://formbricks.com/discord)**

---
