📊 How To Display An In-App Survey In Next.js 13 With Supabase And Formbricks 🤝🛠️
Tags: opensource, hacktoberfest, webdev, frontend
Published: 2023-10-21 12:01:53

Once a user has successfully completed the signup process for your application, you might consider initiating an onboarding segmentation survey for your users right away. This approach enables you to gain a deeper understanding of your users.

## TL;DR

In this article, you'll discover the process of implementing authentication and protected routes using [Supabase](https://supabase.com/docs). Following that, you'll explore how to effortlessly integrate an onboarding segmentation survey into your application.

When you are ready, let's dive in.

![Spongebob is ready](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v27yxlijaqf0vghulxqs.gif)

## Overview

In this article, you will learn how to:

1. Implement authentication and protected routes with Supabase
2. Implement an in-app onboarding segmentation survey with Formbricks.

## 1. How to implement authentication in Next.js 13 with Supabase

If you are unfamiliar with Supabase, it is an open-source alternative to Firebase. Among its array of products, one of the key features we will delve into is its [authentication](https://supabase.com/docs/guides/auth) feature.

We'll start by signing in to the [dashboard](https://supabase.com/dashboard/projects) to create a project. Your dashboard looks this if you have not created a project before:

![Supabase dashboard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdv94ttkakiia7u36t1d.png)

Next, go ahead and create your project by clicking the `new project` button. Name your project however you want; I'll name mine `Auth-with-inapp-survey` for the purpose of this article.

![Create new project on supabase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzwlm52u1ggkzf9og12z.png)

Hit the `create new project` button when you are done, your new project will then appear on your dashboard, this way:

![New project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttsxz77q4o06jb97mevq.png)

With your project successfully created, the next step is to set up your `Next.js` project. Supabase simplifies this process by offering a pre-configured `Next.js` project with `Supabase-auth`, `TypeScript`, and `Tailwind CSS`. To create this project, run the following command in your terminal:

```
npx create-next-app -e with-supabase auth-with-inapp-survey
```

This command will set up your `Next.js` project, integrating it with `Supabase-auth` and the necessary configurations. Although `Tailwind CSS` is included, for the purposes of this article, we don't need to use it.

The advantage of creating a `Next.js` project that comes pre-configured with `Supabase` is that it streamlines the authentication setup for you. This includes setting up functionalities like sign-up, sign-in, log-out, and even a login page, as illustrated in the image below:


![Supabase configured project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ae1qniqnjhh5h04srl0g.png)

Pretty cool right :face_with_cowboy_hat: 

All you need to do is duplicate the `.env.local.example` file within your project using the following command:

```
cp .env.local.example .env.local
```

Then, recover your `supabase URL` and `Anon key` from your project's [API settings.](https://supabase.com/dashboard/project/_/settings/api)

```
NEXT_PUBLIC_SUPABASE_URL=<your-supabase-url>
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-supabase-anon-key>
```

Launch your application, and it will start on your `localhost` at `port 3000`. Your home page will display the following content, and it also includes a link to the pre-configured `login` page. 


![Home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rymayoqivnhjdjogd4wx.png)

Although for this tutorial I would prefer to set my `login` page as the home page - the `index` page. If you also share this preference, follow these steps:

1. Clear the content on the `index` page and paste the content from the `login` page into it.

2. Move the `messages.tsx` file from your `login` folder to the `components` folder. Once this is done, you can safely delete the `login` folder.

3. However, there are a few more adjustments required in your `auth` files to adapt to the new route since the `login` route now serves as the `index` page.

   In the `sign-up/route.ts`, make the following modification:

  ```tsx
// Rest of your code
    export async function POST(request: Request) {
  // Rest of your code
  if (error) {
    return NextResponse.redirect(
      `${requestUrl.origin}?error=Could not authenticate user`,
      {
        // A 301 status is required to redirect from a POST to a GET route
        status: 301,
      }
    );
  }

  return NextResponse.redirect(
    `${requestUrl.origin}?message=Check email to continue the sign-in process`,
    {
      // A 301 status is required to redirect from a POST to a GET route
      status: 301,
    }
  );
 }
```

  In the `sign-out/route.ts`:

```ts
// Rest of the code
export async function POST(request: Request) {
  // Rest of the code
  return NextResponse.redirect(`${requestUrl.origin}`, {
    // A 301 status is required to redirect from a POST to a GET route
    status: 301,
  });
}
```

  In the `sign-in/route.ts`:

```ts
// Rest of the code
export async function POST(request: Request) {
  // Rest of the code
  if (error) {
    return NextResponse.redirect(
      `${requestUrl.origin}?error=Could not authenticate user`,
      {
        // A 301 status is required to redirect from a POST to a GET route
        status: 301,
      }
    );
  }
  return NextResponse.redirect(`${requestUrl.origin}/dashboard`, {
    // A 301 status is required to redirect from a POST to a GET route
    status: 301,
  });
}
```

Note that in the `sign-in` route, we redirected to the `dashboard` page in the return statement, although we won't implement a `dashboard` page for this tutorial. This just ensures that the user is directed to the `dashboard` page after the `sign-in` process is completed.

Finally, in the `callback/route.ts`:

```ts
// Rest of the code
export async function GET(request: Request) {
  // Rest of the code
  // URL to redirect to after the sign-in process completes
  return NextResponse.redirect(`${requestUrl.origin}/onboarding`);
```

After a user attempts to sign-up on the app, the user will have to confirm his email. Upon successful email confirmation, the user will be automatically redirected to the URL specified in the `return` statement of the `callback` function which is the onboarding page.

These modifications will align your authentication routes with the new setup where the `login` page serves as the initial page.

Now that we've completed these steps, let's proceed with implementing our onboarding page.

To create the onboarding page, navigate to the root app directory, and follow the structure depicted below:

![Onboarding page structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7xkt6gcfn2wzuwwflehb.png)

Before we move on to implement the in-app survey, it's essential to ensure that our onboarding page is protected before a user signs up. After all, what's authentication without protected routes, right? 

Fortunately, Supabase provides a straightforward solution for handling this with server components.

Within your `page.tsx` file for the onboarding page, insert the following code:

```tsx
import LogoutButton from "@/components/LogoutButton";
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

export default async function Onboarding() {
  const supabase = createServerComponentClient({ cookies });
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    redirect("/");
  }

  return (
    <div>
      <LogoutButton />
      <p>Hello</p>
    </div>
  );
}
```

In this code, we create a new Supabase client using `createServerComponentClient`, which takes `cookies` as a parameter. This client is then assigned to the variable `supabase`.

> Note: We use `cookies` to store user sessions as opposed to localStorage in server components because you can't access localStorage in server components. Kudos to Supabase for this solution! :thumbsup: 

The subsequent code block:

```tsx
const { data: { session },} = await supabase.auth.getSession();
```

is used to check if a user session exists. If a session exists, the user can access the onboarding page without any issues. However, if the `session` is absent, the `if` statement will be triggered, redirecting the user back to the login page.

I've also imported the `logoutButton` component into this page in case you want to explore how the sign-in/sign-out process works.

Now, let's focus on implementing our onboarding segmentation survey in the onboarding page. This way, users will encounter it right after signing up. The following section will provide a step-by-step guide on how to do this.


## How to implement an in-app onboarding segmentation survey with Formbricks.

Thanks to [Formbricks](https://formbricks.com/), we do not have to build this from scratch :clap: 

### Formbricks: The only open-source solution for in-app surveys

Formbricks is an open-source survey software that helps businesses create and send different kinds of in-app surveys. Formbricks is easy to use and integrates with any web, mobile, or desktop application. Support us by [giving us a star](https://github.com/formbricks/formbricks), it helps us build our community. 

**P.S**: Formbricks is offering swag for Hacktoberfest, and you also have the opportunity to win a Macbook Air! [Come and participate!](https://formbricks.com/formtribe) 

![Hacktoberfest image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbyb1pwkr2jf7rutpvue.png)

Moving forward, here's a concise preview of the steps we're about to cover:

1. Start by registering an account on the Formbricks platform.
2. Customize your onboarding survey according to your preferences.
3. Seamlessly integrate Formbricks into your application.
4. Incorporate your in-app onboarding survey.

### 1. Customize your onboarding survey

Upon creating your account on [Formbricks](https://formbricks.com), you'll be directed to your dashboard, where you'll find a variety of survey templates. For this tutorial, select the onboarding segmentation survey template as that's what we'll be using.


![Onboarding segmentation survey](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8ucwr2iqz4ica01n4y1.png)

Next, you'll be taken to a page where you can edit and tailor this survey to meet your specific requirements. Here, you'll encounter three pre-customized question cards, and you have the option to add more questions if necessary.

![Customize survey](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sokwsenpdp28ybwk0m1d.png)

It's important to note that any modifications made to each question card are instantly reflected in the preview.

Once you've completed your question editing, navigate to the "Settings" tab located adjacent to the "Questions" tab. In this section, you can configure the survey to align with your specific needs.

For the "How to Ask" card, ensure that the web app option is selected.

![How to ask](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4r49w4de3ax131yk6tgr.png)

Another crucial configuration is the survey trigger. Here, you'll define how and when you want your survey to be triggered. To align with the flow of our project and display the survey whenever a user reaches the onboarding page we've implemented, we will choose to trigger the survey only when a user navigates to the onboarding page.

To set up this process, begin by selecting the dropdown and choosing the "Add action" option. This action will trigger a modal to appear:

![Modal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pjqqqljak7ewfcwxzhg.gif)

Complete the fields in the modal as illustrated below. Feel free to customize these details according to your preferences:

![Filled modal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufftiiela3atbqul9561.png)

Please note that in this step, we need to select the "Page URL" option, which allows us to specify the URL where the survey should be displayed. As shown, I've filled the URL field with `https:localhost:3000/onboarding`.

Once you've provided the necessary information, click the "Track Action" button and then select the option from the dropdown:

![Dropdown](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uccjb2udgl1owz21abz4.gif)

Another card to note is the "styling" card. This card enables you to style your survey to align with your UI requirements.

Upon completing the setup, click the "Publish" button located at the top right corner of the page. This action will redirect you to a page displaying your survey analytics.

Next, we will delve into how to establish a connection between your web app and Formbricks.

### Connecting Your Web App and Formbricks

In the settings page, navigate to the "setup checklist" tab found in the sidebar. This page contains all the necessary steps for connecting your web app to Formbricks.

You'll also notice a widget status that informs you whether your app has been successfully connected or not. At this point, since it hasn't been connected, it will be displayed like this:

![Widget status](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9a8uv4gymxnsvuknwb8.png)

To establish the connection, follow these steps:

1. Install the Formbrick widget in your web application using the following command:

   ```npm
   npm install @formbricks/js --save
   ```

2. Create a client component, `formbricks.tsx`, in the root app folder, and insert the following code into it:

   ```tsx
   "use client";
   import formbricks from "@formbricks/js";
   import { usePathname, useSearchParams } from "next/navigation";
   import { useEffect } from "react";

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

     useEffect(() => {
       formbricks.init({
         environmentId: "<environment-id>",
         apiHost: "https://app.formbricks.com",
         debug: true, // remove when in production
       });
     }, []);

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

     return null;
   }
   ```

   The value of your `environmentId` can be obtained from your setup checklist page. I've intentionally omitted it here as it's meant to remain private.

   
![EnvironmentId](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kyqfnqf2egxng1zmeof6.png)

3. Finally, in your `app/layout.tsx` file, import the `formbricks.tsx` file and render it as shown below:

   ```tsx
   import FormbricksProvider from './formbricks'

   export default function RootLayout({
     children,
   }: {
     children: React.ReactNode
   }) {
     return (
       <html lang="en">
         <FormbricksProvider /> {/* Render here */}
         <body>
           {/* Rest of the code here */}
         </body>
       </html>
     )
   }
   ```

   Upon restarting your web app, the status indicator will be updated to the following:

   
   ![updated status](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvf5ote0kckm7hzri7w0.png)
   Additionally, you'll see in your console that your app has successfully been connected to Formbricks.

   
   ![console connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brz0jbnx6dqi59viste6.png)
   You can now test this by attempting to sign up for your app. When you click the sign-up button, you will receive a notification that a mail has been sent to your email address for verification.
 
   ![Login page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qmepvbadh5t0qp6gdosm.png)
   Upon verification, you will be redirected to the 'onboarding' page as intended. There, your onboarding segmentation survey will appear just as we've implemented:

![Onboarding survey](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0xcv2qgqqzp6ktgua5t.png)

And there you have it, you've learned how straightforward it is to segment your users using Formbricks.

## Final Notes

Throughout this article, you've gained insights into:

- Implementing authentication and protected routes with Supabase.
- Integrating an onboarding segmentation survey into your web app with Formbricks.

You can access the code for this project [here](https://github.com/SiR-PENt/auth-with-inapp-survey).

Additionally, don't forget to support us by [giving us a star](https://github.com/formbricks/formbricks) :star:!