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.
Overview
In this article, you will learn how to:
- Implement authentication and protected routes with Supabase
- 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:
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.
Hit the create new project
button when you are done, your new project will then appear on your dashboard, this way:
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:
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.
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.
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:
Clear the content on the
index
page and paste the content from thelogin
page into it.Move the
messages.tsx
file from yourlogin
folder to thecomponents
folder. Once this is done, you can safely delete thelogin
folder.However, there are a few more adjustments required in your
auth
files to adapt to the new route since thelogin
route now serves as theindex
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,
}
);
}
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,
});
}
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,
});
}
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`);
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:
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>
);
}
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();
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!
Moving forward, here's a concise preview of the steps we're about to cover:
- Start by registering an account on the Formbricks platform.
- Customize your onboarding survey according to your preferences.
- Seamlessly integrate Formbricks into your application.
- 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.
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.
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.
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:
Complete the fields in the modal as illustrated below. Feel free to customize these details according to your preferences:
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:
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:
To establish the connection, follow these steps:
- Install the Formbrick widget in your web application using the following command:
npm install @formbricks/js --save
- 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;
}
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.
- Finally, in your
app/layout.tsx
file, import theformbricks.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>
)
}
Upon restarting your web app, the status indicator will be updated to the following:
Additionally, you'll see in your console that your app has successfully been connected to Formbricks.
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.
Upon verification, you will be redirected to the 'onboarding' page as intended. There, your onboarding segmentation survey will appear just as we've implemented:
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)
Great write up Ola, thank you! :)