DEV Community

Cover image for πŸ“Š How To Display An In-App Survey In Next.js 13 With Supabase And Formbricks πŸ€πŸ› οΈ
Olasunkanmi Balogun
Olasunkanmi Balogun

Posted on • Updated on

πŸ“Š How To Display An In-App Survey In Next.js 13 With Supabase And Formbricks πŸ€πŸ› οΈ

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

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

We'll start by signing in to the dashboard to create a project. Your dashboard looks this if you have not created a project before:

Supabase dashboard

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

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

New project

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

Then, recover your supabase URL and Anon key from your project's API settings.

NEXT_PUBLIC_SUPABASE_URL=<your-supabase-url>
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-supabase-anon-key>
Enter fullscreen mode Exit fullscreen mode

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

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:

// 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,
    }
  );
 }
Enter fullscreen mode Exit fullscreen mode

In the sign-out/route.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,
  });
}
Enter fullscreen mode Exit fullscreen mode

In the sign-in/route.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,
  });
}
Enter fullscreen mode Exit fullscreen mode

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:

// 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`);
Enter fullscreen mode Exit fullscreen mode

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

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:

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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! πŸ‘

The subsequent code block:

const { data: { session },} = await supabase.auth.getSession();
Enter fullscreen mode Exit fullscreen mode

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, we do not have to build this from scratch πŸ‘

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, 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!

Hacktoberfest image

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

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

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

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

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

Filled modal

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

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

To establish the connection, follow these steps:

  1. Install the Formbrick widget in your web application using the following command:
   npm install @formbricks/js --save
Enter fullscreen mode Exit fullscreen mode
  1. Create a client component, formbricks.tsx, in the root app folder, and insert the following code into it:
   "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;
   }
Enter fullscreen mode Exit fullscreen mode

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

  1. Finally, in your app/layout.tsx file, import the formbricks.tsx file and render it as shown below:
   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>
     )
   }
Enter fullscreen mode Exit fullscreen mode

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

updated status
Additionally, you'll see in your console that your app has successfully been connected to Formbricks.

console connection
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
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

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.

Additionally, don't forget to support us by giving us a star ⭐!

Top comments (1)

Collapse
 
jobenjada profile image
Johannes

Great write up Ola, thank you! :)