import { Layout } from "@/components/docs/Layout";

export const meta = {
  title: "Setting up Formbricks SDK with Next.js",
  description: "Integrate Formbricks SDK into your Next.js app for seamless in-product micro-surveys. Follow our step-by-step guide to enhance user feedback and product experience.",
};

This guide will walk you through the process of integrating the Formbricks SDK into a Next.js application. As the Formbricks SDK only works on the client side, it's essential to ensure proper integration to avoid any issues.

## Introduction

Formbricks SDK allows you to seamlessly integrate in-product micro-surveys into your Next.js application. By following the steps outlined in this guide, you'll be able to gather valuable insights from your users and improve your product experience.

## Prerequisites

Before getting started, make sure you have:

1. A Next.js application 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.

## Installing Formbricks SDK

First, you need to install the Formbricks SDK using one of the following commands:

```bash
npm install --save @formbricks/js
# or
yarn add @formbricks/js
# or
pnpm add @formbricks/js
```

## Integrating Formbricks SDK with Next.js

Update your App component in the \_app.ts file like so:

```tsx
import "@/styles/globals.css";
import type { AppProps } from "next/app";
import { useEffect } from "react";
import { useRouter } from "next/router";
import formbricks from "@formbricks/js";

if (typeof window !== "undefined") {
  formbricks.init({
    environmentId: "your-environment-id",
    apiHost: "your-api-host", // e.g. https://app.formbricks.com
    logLevel: "debug", // remove when in production
  });
}

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} />;
}
```

**What are we doing here?**
First we need to initialize the Formbricks SDK, making sure 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.

That's it! 🎉

You should now see that the Widget Status in the setup checklist updated accordingly:

If it doesnt work, please [join our Discord](https://formbricks.com/discord) and let us know!

You have now successfully integrated the Formbricks SDK into your Next.js application. You can start creating and customizing in-product micro-surveys to gather valuable feedback from your users and improve your product experience.

export default ({ children }) => <Layout meta={meta}>{children}</Layout>;
