Formbricks Open source Forms & Surveys Logo

Getting Started

Setting up Formbricks SDK with Next.js

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:

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:

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 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.

Was this page helpful?
Previous
Quickstart

Need help? 🤓

Join our Discord and ask away. We're happy to help where we can!

Join Discord