Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Persist onboarding state

Tim Wilsonda8c4c0d66c1
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
index 6803987834..2d278c8008 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/custom/form.tsx
@@ -1,6 +1,7 @@
"use client";
import { AddEditDomainForm } from "@/ui/domains/add-edit-domain-form";
+import { LaterButton } from "../../../later-button";
import { useOnboardingProgress } from "../../../use-onboarding-progress";
export function Form() {
@@ -15,13 +16,7 @@ export function Form() {
showAdvancedOptions={false}
showDomainTypeOptions={false}
/>
- <button
- type="button"
- onClick={() => continueTo("invite")}
- className="mt-4 w-full text-center text-sm text-gray-500 transition-colors hover:text-gray-700"
- >
- I'll do this later
- </button>
+ <LaterButton next="invite" className="mt-4" />
</div>
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
index e2871cba2d..f6d849e5d0 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
@@ -6,10 +6,11 @@ import { Button } from "@dub/ui";
import { Globe2 } from "@dub/ui/src/icons";
import { cn } from "@dub/utils";
import { useEffect, useState } from "react";
+import { LaterButton } from "../../later-button";
import { useOnboardingProgress } from "../../use-onboarding-progress";
export function DomainSelector() {
- const { continueTo } = useOnboardingProgress();
+ const { continueTo, isExecuting } = useOnboardingProgress();
return (
<div>
@@ -26,15 +27,10 @@ export function DomainSelector() {
type="button"
variant="primary"
onClick={() => continueTo("domain/custom")}
+ loading={isExecuting}
text="Continue"
/>
- <button
- type="button"
- onClick={() => continueTo("invite")}
- className="mt-4 w-full text-center text-sm text-gray-500 transition-colors hover:text-gray-700"
- >
- I'll do this later
- </button>
+ <LaterButton next="invite" className="mt-4" />
</div>
</div>
);
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/invite/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/invite/form.tsx
index 00aa5564c8..757c5059d2 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/invite/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/invite/form.tsx
@@ -1,6 +1,7 @@
"use client";
import { InviteTeammatesForm } from "@/ui/workspaces/invite-teammates-form";
+import { LaterButton } from "../../later-button";
import { useOnboardingProgress } from "../../use-onboarding-progress";
export function Form() {
@@ -13,13 +14,7 @@ export function Form() {
continueTo("plan");
}}
/>
- <button
- type="button"
- onClick={() => continueTo("plan")}
- className="mt-4 w-full text-center text-sm text-gray-500 transition-colors hover:text-gray-700"
- >
- I'll do this later
- </button>
+ <LaterButton next="plan" className="mt-4" />
</div>
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/link/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/link/form.tsx
index 85c47fa233..ccaf8cb21c 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/link/form.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/link/form.tsx
@@ -14,6 +14,7 @@ import { Controller, useForm } from "react-hook-form";
import { toast } from "sonner";
import { mutate } from "swr";
import { useDebounce } from "use-debounce";
+import { LaterButton } from "../../later-button";
import { useOnboardingProgress } from "../../use-onboarding-progress";
type FormData = {
@@ -88,102 +89,105 @@ export function Form() {
}, [debouncedUrl]);
return (
- <form
- className="flex w-full flex-col gap-y-6"
- onSubmit={handleSubmit(async (data) => {
- if (!workspaceId) {
- toast.error("Failed to get workspace data.");
- return;
- }
+ <>
+ <form
+ className="flex w-full flex-col gap-y-6"
+ onSubmit={handleSubmit(async (data) => {
+ if (!workspaceId) {
+ toast.error("Failed to get workspace data.");
+ return;
+ }
- const {
- url,
- link: { domain, key },
- } = data;
-
- const res = await fetch(`/api/links?workspaceId=${workspaceId}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ url, domain, key }),
- });
-
- if (!res.ok) {
- const { error } = await res.json();
- if (error) {
- if (error.message.includes("Upgrade to")) {
- toast.custom(() => (
- <UpgradeRequiredToast
- title={`You've discovered a ${nextPlan.name} feature!`}
- message={error.message}
- />
- ));
- } else {
- toast.error(error.message);
+ const {
+ url,
+ link: { domain, key },
+ } = data;
+
+ const res = await fetch(`/api/links?workspaceId=${workspaceId}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ url, domain, key }),
+ });
+
+ if (!res.ok) {
+ const { error } = await res.json();
+ if (error) {
+ if (error.message.includes("Upgrade to")) {
+ toast.custom(() => (
+ <UpgradeRequiredToast
+ title={`You've discovered a ${nextPlan.name} feature!`}
+ message={error.message}
+ />
+ ));
+ } else {
+ toast.error(error.message);
+ }
}
+ throw new Error(error);
}
- throw new Error(error);
- }
- await mutate(
- (key) => typeof key === "string" && key.startsWith("/api/links"),
- undefined,
- { revalidate: true },
- );
- const result = await res.json();
- posthog.capture("link_created", result);
-
- continueTo("domain");
- })}
- >
- <DestinationUrlInput domains={domains} {...register("url")} />
- <Controller
- control={control}
- name="link"
- render={({ field }) => (
- <ShortLinkInput
- onChange={(d) => field.onChange({ ...field.value, ...d })}
- domain={link.domain}
- _key={link.key}
- data={{ url, title: "", description: "" }}
- saving={isSubmitting}
- loading={loading}
- domains={domains}
- />
- )}
- />
- <div className="flex flex-col gap-2">
- <span className="block text-sm font-medium text-gray-700">
- Link Preview
- </span>
- <div className="relative aspect-[1.91/1] w-full overflow-hidden rounded-md border border-gray-300 bg-gray-100">
- {previewImage ? (
- <img
- src={previewImage}
- alt="Preview"
- className="relative size-full rounded-[inherit] object-cover"
+ await mutate(
+ (key) => typeof key === "string" && key.startsWith("/api/links"),
+ undefined,
+ { revalidate: true },
+ );
+ const result = await res.json();
+ posthog.capture("link_created", result);
+
+ await continueTo("domain");
+ })}
+ >
+ <DestinationUrlInput domains={domains} {...register("url")} />
+ <Controller
+ control={control}
+ name="link"
+ render={({ field }) => (
+ <ShortLinkInput
+ onChange={(d) => field.onChange({ ...field.value, ...d })}
+ domain={link.domain}
+ _key={link.key}
+ data={{ url, title: "", description: "" }}
+ saving={isSubmitting}
+ loading={loading}
+ domains={domains}
/>
- ) : (
- <div className="relative flex size-full flex-col items-center justify-center space-y-4 bg-white">
- <Photo className="h-8 w-8 text-gray-400" />
- <p className="text-sm text-gray-400">
- Enter a link to generate a preview.
- </p>
- </div>
- )}
- {loadingPreviewImage && (
- <div className="absolute inset-0 z-[5] flex items-center justify-center rounded-[inherit] bg-white">
- <LoadingCircle />
- </div>
)}
+ />
+ <div className="flex flex-col gap-2">
+ <span className="block text-sm font-medium text-gray-700">
+ Link Preview
+ </span>
+ <div className="relative aspect-[1.91/1] w-full overflow-hidden rounded-md border border-gray-300 bg-gray-100">
+ {previewImage ? (
+ <img
+ src={previewImage}
+ alt="Preview"
+ className="relative size-full rounded-[inherit] object-cover"
+ />
+ ) : (
+ <div className="relative flex size-full flex-col items-center justify-center space-y-4 bg-white">
+ <Photo className="h-8 w-8 text-gray-400" />
+ <p className="text-sm text-gray-400">
+ Enter a link to generate a preview.
+ </p>
+ </div>
+ )}
+ {loadingPreviewImage && (
+ <div className="absolute inset-0 z-[5] flex items-center justify-center rounded-[inherit] bg-white">
+ <LoadingCircle />
+ </div>
+ )}
+ </div>
</div>
- </div>
- <Button
- type="submit"
- text="Create link"
- loading={isSubmitting || isSubmitSuccessful}
- />
- </form>
+ <Button
+ type="submit"
+ text="Create link"
+ loading={isSubmitting || isSubmitSuccessful}
+ />
+ </form>
+ <LaterButton next="domain" className="mt-4" />
+ </>
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
index f985f05e11..ab0812d1ad 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/plan/plan-selector.tsx
@@ -7,6 +7,7 @@ import { Badge } from "@dub/ui";
import { ToggleGroup } from "@dub/ui/src/toggle-group";
import { PRO_PLAN, SELF_SERVE_PAID_PLANS } from "@dub/utils";
import { useState } from "react";
+import { LaterButton } from "../../later-button";
import { useOnboardingProgress } from "../../use-onboarding-progress";
export function PlanSelector() {
@@ -46,13 +47,7 @@ export function PlanSelector() {
>
Looking for enterprise?
</a>
- <button
- type="button"
- onClick={() => finish()}
- className="w-full text-center text-sm text-gray-500 transition-colors hover:text-gray-700"
- >
- I'll pick a plan later
- </button>
+ <LaterButton next="finish">I'll pick a plan later</LaterButton>
</div>
</div>
);
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/later-button.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/later-button.tsx
new file mode 100644
index 0000000000..721b735a29
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/later-button.tsx
@@ -0,0 +1,35 @@
+import { OnboardingStep } from "@/lib/onboarding/types";
+import { LoadingSpinner } from "@dub/ui/src/icons";
+import { cn } from "@dub/utils";
+import { PropsWithChildren } from "react";
+import { useOnboardingProgress } from "./use-onboarding-progress";
+
+export function LaterButton({
+ next,
+ className,
+ children,
+}: PropsWithChildren<{ next: OnboardingStep | "finish"; className?: string }>) {
+ const { continueTo, finish, isLoading, isSuccessful } =
+ useOnboardingProgress();
+
+ return (
+ <button
+ type="button"
+ onClick={() => (next === "finish" ? finish() : continueTo(next))}
+ className={cn(
+ "mx-auto flex w-fit items-center gap-2 text-center text-sm text-gray-500 transition-colors enabled:hover:text-gray-700",
+ className,
+ )}
+ disabled={isLoading || isSuccessful}
+ >
+ <LoadingSpinner
+ className={cn(
+ "size-3 transition-opacity",
+ !(isLoading || isSuccessful) && "opacity-0",
+ )}
+ />
+ {children || "I'll do this later"}
+ <div className="w-3" />
+ </button>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/next-button.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/next-button.tsx
index 5d9d0600d6..77d4867ada 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/next-button.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/next-button.tsx
@@ -1,16 +1,21 @@
"use client";
+import { OnboardingStep } from "@/lib/onboarding/types";
import { Button, ButtonProps } from "@dub/ui";
import { useOnboardingProgress } from "./use-onboarding-progress";
-export function NextButton({ step, ...rest }: { step: string } & ButtonProps) {
- const { continueTo } = useOnboardingProgress();
+export function NextButton({
+ step,
+ ...rest
+}: { step: OnboardingStep } & ButtonProps) {
+ const { continueTo, isLoading, isSuccessful } = useOnboardingProgress();
return (
<Button
variant="primary"
text="Next"
onClick={() => continueTo(step)}
+ loading={isLoading || isSuccessful}
{...rest}
/>
);
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
index b2c9dadb26..d9c4e1819b 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/use-onboarding-progress.ts
@@ -1,20 +1,63 @@
+import { setOnboardingProgress } from "@/lib/actions/set-onboarding-progress";
+import { OnboardingStep } from "@/lib/onboarding/types";
import useWorkspace from "@/lib/swr/use-workspace";
+import { useAction } from "next-safe-action/hooks";
import { useRouter } from "next/navigation";
+import { useCallback } from "react";
+import { toast } from "sonner";
const PRE_SLUG_STEPS = ["workspace"];
export function useOnboardingProgress() {
const router = useRouter();
-
const { slug } = useWorkspace();
- return {
- continueTo: (step: string, { slug: slugParam }: { slug?: string } = {}) => {
+ const { executeAsync, isExecuting, hasSucceeded } = useAction(
+ setOnboardingProgress,
+ {
+ onSuccess: () => {
+ console.log("Onboarding progress updated");
+ },
+ onError: ({ error }) => {
+ toast.error("Failed to update onboarding progress. Please try again.");
+ console.error("Failed to update onboarding progress", Error);
+ },
+ },
+ );
+
+ const continueTo = useCallback(
+ async (
+ step: OnboardingStep,
+ { slug: slugParam }: { slug?: string } = {},
+ ) => {
+ const result = await executeAsync({
+ onboardingStep: step,
+ });
+
+ if (result?.serverError) return;
+
const queryParams = PRE_SLUG_STEPS.includes(step)
? ""
: `?slug=${slugParam || slug}`;
router.push(`/onboarding/${step}${queryParams}`);
},
- finish: () => router.push(`/${slug}`),
+ [executeAsync, router, slug],
+ );
+
+ const finish = useCallback(async () => {
+ const result = await executeAsync({
+ onboardingStep: null,
+ });
+
+ if (result?.serverError) return;
+
+ router.push(`/${slug}`);
+ }, [executeAsync, router, slug]);
+
+ return {
+ continueTo,
+ finish,
+ isLoading: isExecuting,
+ isSuccessful: hasSucceeded,
};
}
diff --git a/apps/web/lib/actions/safe-action.ts b/apps/web/lib/actions/safe-action.ts
index 07fd3f490e..bca3962a72 100644
--- a/apps/web/lib/actions/safe-action.ts
+++ b/apps/web/lib/actions/safe-action.ts
@@ -16,6 +16,20 @@ export const actionClient = createSafeActionClient({
},
});
+export const authUserActionClient = actionClient.use(async ({ next }) => {
+ const session = await getSession();
+
+ if (!session?.user.id) {
+ throw new Error("Unauthorized: Login required.");
+ }
+
+ return next({
+ ctx: {
+ user: session.user,
+ },
+ });
+});
+
export const authActionClient = actionClient.use(
async ({ next, clientInput }) => {
const session = await getSession();
diff --git a/apps/web/lib/actions/set-onboarding-progress.ts b/apps/web/lib/actions/set-onboarding-progress.ts
new file mode 100644
index 0000000000..a493747130
--- /dev/null
+++ b/apps/web/lib/actions/set-onboarding-progress.ts
@@ -0,0 +1,33 @@
+"use server";
+
+import { z } from "zod";
+import { ONBOARDING_STEPS } from "../onboarding/types";
+import { prisma } from "../prisma";
+import { authUserActionClient } from "./safe-action";
+
+// Generate a new client secret for an integration
+export const setOnboardingProgress = authUserActionClient
+ .schema(
+ z.object({
+ onboardingStep: z.enum(ONBOARDING_STEPS).nullable(),
+ }),
+ )
+ .action(async ({ ctx, parsedInput }) => {
+ const { onboardingStep } = parsedInput;
+
+ try {
+ await prisma.user.update({
+ where: {
+ id: ctx.user.id,
+ },
+ data: {
+ onboardingStep,
+ },
+ });
+ } catch (e) {
+ console.error("Failed to update onboarding step", e);
+ throw new Error("Failed to update onboarding step");
+ }
+
+ return { success: true };
+ });
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index 7b8bf267a3..b1a412bc9b 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -2,6 +2,7 @@ import { parse } from "@/lib/middleware/utils";
import { NextRequest, NextResponse } from "next/server";
import NewLinkMiddleware from "./new-link";
import { getDefaultWorkspace } from "./utils/get-default-workspace";
+import { getRefreshedUser } from "./utils/get-refreshed-user";
import { getUserViaToken } from "./utils/get-user-via-token";
export default async function AppMiddleware(req: NextRequest) {
@@ -26,6 +27,8 @@ export default async function AppMiddleware(req: NextRequest) {
// if there's a user
} else if (user) {
+ const refreshedUser = await getRefreshedUser(user);
+
// /new is a special path that creates a new link (or workspace if the user doesn't have one yet)
if (path === "/new") {
return NewLinkMiddleware(req, user);
@@ -36,11 +39,35 @@ export default async function AppMiddleware(req: NextRequest) {
user.createdAt &&
new Date(user.createdAt).getTime() > Date.now() - 10000 &&
// here we include the root page + /new (since they're going through welcome flow already)
- path !== "/welcome" &&
+ !path.startsWith("/onboarding") &&
// if the user was invited to a workspace, don't show the welcome page – redirect straight to the workspace
!isWorkspaceInvite
) {
- return NextResponse.redirect(new URL("/welcome", req.url));
+ return NextResponse.redirect(new URL("/onboarding", req.url));
+
+ // Onboarding redirects
+ } else if (
+ !isWorkspaceInvite &&
+ !path.startsWith("/onboarding") &&
+ refreshedUser &&
+ // User has onboarding step
+ (refreshedUser.onboardingStep ||
+ // User has no workspaces and was created less than an hour ago
+ (refreshedUser.projects.length === 0 &&
+ new Date(user.createdAt).getTime() > Date.now() - 60 * 60 * 1000))
+ ) {
+ const defaultWorkspace = await getDefaultWorkspace(user);
+
+ let step = refreshedUser.onboardingStep;
+ if (defaultWorkspace) {
+ // Skip workspace step if user already has a workspace (maybe there was an error updating the onboarding step)
+ step = step === "workspace" ? "link" : step;
+ return NextResponse.redirect(
+ new URL(`/onboarding/${step}?slug=${defaultWorkspace}`, req.url),
+ );
+ } else {
+ return NextResponse.redirect(new URL(`/onboarding/${step}`, req.url));
+ }
// if the path is / or /login or /register, redirect to the default workspace
} else if (
diff --git a/apps/web/lib/middleware/utils/get-default-workspace.ts b/apps/web/lib/middleware/utils/get-default-workspace.ts
index de8def763c..fb4de5e53b 100644
--- a/apps/web/lib/middleware/utils/get-default-workspace.ts
+++ b/apps/web/lib/middleware/utils/get-default-workspace.ts
@@ -1,31 +1,15 @@
-import { prismaEdge } from "@/lib/prisma/edge";
import { UserProps } from "@/lib/types";
+import { getRefreshedUser } from "./get-refreshed-user";
export async function getDefaultWorkspace(user: UserProps) {
let defaultWorkspace = user?.defaultWorkspace;
if (!defaultWorkspace) {
- const refereshedUser = await prismaEdge.user.findUnique({
- where: {
- id: user.id,
- },
- select: {
- defaultWorkspace: true,
- projects: {
- select: {
- project: {
- select: {
- slug: true,
- },
- },
- },
- take: 1,
- },
- },
- });
+ const refreshedUser = await getRefreshedUser(user);
+
defaultWorkspace =
- refereshedUser?.defaultWorkspace ||
- refereshedUser?.projects[0]?.project?.slug ||
+ refreshedUser?.defaultWorkspace ||
+ refreshedUser?.projects[0]?.project?.slug ||
undefined;
}
diff --git a/apps/web/lib/middleware/utils/get-refreshed-user.ts b/apps/web/lib/middleware/utils/get-refreshed-user.ts
new file mode 100644
index 0000000000..bcfa896aab
--- /dev/null
+++ b/apps/web/lib/middleware/utils/get-refreshed-user.ts
@@ -0,0 +1,26 @@
+import { prismaEdge } from "@/lib/prisma/edge";
+import { UserProps } from "@/lib/types";
+
+export async function getRefreshedUser(user: UserProps) {
+ const refreshedUser = await prismaEdge.user.findUnique({
+ where: {
+ id: user.id,
+ },
+ select: {
+ defaultWorkspace: true,
+ onboardingStep: true,
+ projects: {
+ select: {
+ project: {
+ select: {
+ slug: true,
+ },
+ },
+ },
+ take: 1,
+ },
+ },
+ });
+
+ return refreshedUser;
+}
diff --git a/apps/web/lib/onboarding/types.ts b/apps/web/lib/onboarding/types.ts
new file mode 100644
index 0000000000..007ee3de87
--- /dev/null
+++ b/apps/web/lib/onboarding/types.ts
@@ -0,0 +1,10 @@
+export const ONBOARDING_STEPS = [
+ "workspace",
+ "link",
+ "domain",
+ "domain/custom",
+ "invite",
+ "plan",
+] as const;
+
+export type OnboardingStep = (typeof ONBOARDING_STEPS)[number];
diff --git a/apps/web/prisma/schema/schema.prisma b/apps/web/prisma/schema/schema.prisma
index a0d62ed06c..b460e92a46 100644
--- a/apps/web/prisma/schema/schema.prisma
+++ b/apps/web/prisma/schema/schema.prisma
@@ -19,6 +19,7 @@ model User {
passwordHash String?
invalidLoginAttempts Int @default(0)
lockedAt DateTime?
+ onboardingStep String?
accounts Account[]
sessions Session[]