Clerk
Blog

Back

Engineering


Jan 30, 2024

Back

Engineering


Jan 30, 2024

How to Add an Onboarding Flow for your Application with Clerk

Roy Anger

Roy Anger


Leverage Clerk’s customizable session tokens, publicMetadata and Next’s Middleware to create a robust onboarding experience within a few lines of code.


As part of your onboarding flow, you may want to collect extra information from your user and use it to drive your application state. Let’s walk through a quick example using Next.js and TypeScript to show you how simple implementing an onboarding flow can be.

In this guide, you will learn how to:

  1. Add custom claims to your session token
  2. Configure your middleware to read session data
  3. Update with the user’s onboarding state

To see a working example, check out our sample demonstration app here.

The examples below have been pared down to the bare minimum to enable you to easily customize them to your needs, you can build them with the Clerk + Next Quickstart using @clerk/nextjs 4.29.5 and Next 14.0.4.

Let’s get started!

Image showing the user's path if they have completed onboarding, or if they have not.

Add Custom Claims to Your Session Token

Session tokens are JWTs that are generated by Clerk on behalf of your instance, and contain claims that allow you to store data about a user’s session. With Clerk, when a session token exists for a user, it indicates that the user is authenticated, and the associated claims can be retrieved at any time. [Learn More]

First, navigate to Sessions in your Clerk Dashboard and click the ‘Edit’ button. In the modal that opens, there will be a window where you can augment your session token with custom claims.

In there, add the following and hit save:

1
{
2
"metadata": "{{user.public_metadata}}"
3
}

Add metadata to the session

If you haven’t already, we can make the public metadata type information accessible to our application by adding the following to src/types/globals.d.ts:

1
export { };
2
3
declare global {
4
interface CustomJwtSessionClaims {
5
metadata: {
6
onboardingComplete?: boolean;
7
};
8
}
9
}

We have just added custom data to our session token in the Clerk Dashboard and made those claims accessible to our app. Next, we’ll use clerkMiddleware to redirect the user based on onboardingComplete status.

Configure your Next.js middleware to read session data

Clerk's authMiddleware() allows you ton configure access to your routes with fine grained control. You can also retrieve claims directly from the session and redirect your user accordingly. [Learn More]

Add the code sample below to your src/middleware.ts file:

1
import { authMiddleware } from "@clerk/nextjs";
2
import { redirectToSignIn } from "@clerk/nextjs/server";
3
import { NextRequest, NextResponse } from "next/server";
4
5
// This example protects all routes including api/trpc routes
6
// Please edit this to allow other routes to be public as needed.
7
// See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware
8
export default authMiddleware({
9
publicRoutes: ["/"],
10
afterAuth: async (auth, req: NextRequest) => {
11
const { userId, sessionClaims } = auth
12
13
// For user visiting /onboarding, don't try and redirect
14
if (userId && req.nextUrl.pathname === "/onboarding") {
15
return NextResponse.next();
16
}
17
18
// User isn't signed in and the route is private -- redirect to sign-in
19
if (!userId && !auth.isPublicRoute) return redirectToSignIn({ returnBackUrl: req.url })
20
21
// Catch users who doesn't have `onboardingComplete: true` in PublicMetata
22
// Redirect them to the /onboading out to complete onboarding
23
if (userId && !sessionClaims?.metadata?.onboardingComplete) {
24
const onboardingUrl = new URL("/onboarding", req.url);
25
return NextResponse.redirect(onboardingUrl)
26
}
27
28
// User is logged in and the route is protected - let them view.
29
if (userId && !auth.isPublicRoute) return NextResponse.next()
30
31
// If the route is public, anyone can view it.
32
if (auth.isPublicRoute) return NextResponse.next()
33
34
}
35
});
36
37
export const config = {
38
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
39
};

Next, create a layout.tsx file in src/app/onboarding and add the following code to the file. This logic could go in the Middleware, but by adding to the layout.tsx to the route the logic remains in one place. This file can also be expanded to handle multiple steps, if multiple steps are required for an onboarding flow.

1
import { auth } from "@clerk/nextjs/server"
2
import { redirect } from "next/navigation"
3
4
export default function RootLayout({
5
children,
6
}: {
7
children: React.ReactNode
8
}) {
9
10
// Check if a user has completed onboarding
11
// If yes, redirect them to /dashboard
12
if (auth().sessionClaims?.metadata.onboardingComplete === true) {
13
redirect("/dashboard")
14
}
15
16
return <>{children}</>
17
}

Now that we have the logic for where to direct the user, we’ll need a way to track their onboarding status and note it on their session, let’s dig into that now!

Update publicMetadata based on onboarding state

Updating a user's publicMetadata as they progress through the flow will allow us to recognize when they have successfully completed their onboarding and, per the logic above, are now able to access the application. [Learn More]

To do this you need:

  • A method in your backend to securely update the user publicMetadata
  • A process in your frontend with logic to collect and submit all the information for onboarding. In this guide you’ll use an example form.

Add userUpdate method to your backend

First, add a method in your backend, that will be called on form submission and update the user’s publicMetadata accordingly. The example below uses the clerkClient wrapper to interact with the Backend API.

Under src/app/onboarding/_actions.ts add the following code snippet:

1
"use server";
2
3
import { auth, clerkClient } from "@clerk/nextjs/server";
4
5
export const completeOnboarding = async (formData: FormData) => {
6
const { userId } = auth();
7
8
if (!userId) {
9
return { message: "No Logged In User" };
10
}
11
12
try {
13
const res = await clerkClient.users.updateUser(userId, {
14
publicMetadata: {
15
onboardingComplete: true,
16
applicationName: formData.get("applicationName"),
17
applicationType: formData.get("applicationType"),
18
},
19
});
20
return { message: res.publicMetadata };
21
} catch (err) {
22
return { "error": 'There was an error updating the user metadata.' };
23
}
24
};

Now that we have a method to securely update our user’s publicMetadata we can call this server action from a client side form.

Add a form to your frontend

With the backend updateUser method in place, we’ll add a basic page that contains a form to complete the onboarding process.

This example form that will capture an application name (applicationName) and application type of either B2C or B2B (applicationType). This is a very loose example — you can use this step to capture information from the user, sync user data to your database, have the user sign up to a course or subscription, or more.

To implement this logic, insert the following into your src/app/onboarding/page.tsx:

1
"use client";
2
3
import * as React from "react";
4
import { useUser } from "@clerk/nextjs";
5
import { useRouter } from "next/navigation";
6
import { completeOnboarding } from "./_actions";
7
8
export default function OnboardingComponent() {
9
const [error, setError] = React.useState("");
10
const { user } = useUser();
11
const router = useRouter();
12
13
const handleSubmit = async (formData: FormData) => {
14
const res = await completeOnboarding(formData);
15
if (res?.message) {
16
await user?.reload();
17
router.push("/dashboard");
18
}
19
if (res?.error) {
20
setError(res?.error);
21
}
22
};
23
return (
24
<div>
25
<h1>Welcome</h1>
26
<form action={handleSubmit}>
27
<div>
28
<label>Application Name</label>
29
<p>Enter the name of your application.</p>
30
<input type="text" name="applicationName" required />
31
</div>
32
33
<div>
34
<label>Application Type</label>
35
<p>Describe the type of your application.</p>
36
<input type="text" name="applicationType" required />
37
</div>
38
{error && <p className="text-red-600">Error: {error}</p>}
39
<button type="submit">Submit</button>
40
</form>
41
</div>
42
);
43
}

Wrap Up

Your onboarding flow is now complete! 🎉 New users who haven’t yet onboarded will now land on your /onboarding page and, once they have completed onboarding, will be sent through to the dashboard. By using Clerk, which already handles user authentication, we were able to simplify the process of creating a custom user onboarding flow as well.

Clerk's logo

Start now,
no strings attached

Start completely free for up to 10,000 monthly active users and up to 100 monthly active orgs. No credit card required.

Start Building

Pricing built for
businesses of all sizes.

Learn more about our transparent per-user costs to estimate how much your company could save by implementing Clerk.

View pricing
Clerk's logo

Newsletter!

The latest news and updates from Clerk, sent to your inbox.

Clerk logo

Clerk - Complete User Management

TwitterLinkedInGitHubDiscordFacebook

© 2024 Clerk Inc.


product
Components

© 2024 Clerk Inc.