Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): add regional demo redirect (#15483)

annabellscha3887d9419617
diff --git a/web/src/__tests__/server/unit/demoRedirect.servertest.ts b/web/src/__tests__/server/unit/demoRedirect.servertest.ts
new file mode 100644
index 0000000000..fbac26f13a
--- /dev/null
+++ b/web/src/__tests__/server/unit/demoRedirect.servertest.ts
@@ -0,0 +1,287 @@
+const mockEnv = vi.hoisted(() => ({
+ env: {
+ AUTH_DISABLE_SIGNUP: undefined as string | undefined,
+ NEXT_PUBLIC_DEMO_ORG_ID: "demo-org" as string | undefined,
+ NEXT_PUBLIC_DEMO_PROJECT_ID: "demo-project" as string | undefined,
+ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "EU" as
+ | "EU"
+ | "US"
+ | "JP"
+ | "HIPAA"
+ | "DEV"
+ | "STAGING"
+ | undefined,
+ NEXT_PUBLIC_SIGN_UP_DISABLED: "false" as "true" | "false",
+ },
+}));
+
+vi.mock("@/src/env.mjs", () => mockEnv);
+
+const { getServerAuthSessionMock, prismaMock } = vi.hoisted(() => ({
+ getServerAuthSessionMock: vi.fn(),
+ prismaMock: {
+ project: {
+ findUnique: vi.fn(),
+ },
+ },
+}));
+
+vi.mock("@/src/server/auth", () => ({
+ getServerAuthSession: getServerAuthSessionMock,
+}));
+
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: prismaMock,
+}));
+
+import { type GetServerSidePropsContext } from "next";
+import { getServerSideProps as getDemoServerSideProps } from "@/src/pages/demo/[[...path]]";
+
+type DemoCtxOverrides = {
+ resolvedUrl?: string;
+ req?: {
+ cookies?: Partial<Record<string, string>>;
+ headers?: Partial<Record<string, string>>;
+ };
+};
+
+const makeCtx = (overrides: DemoCtxOverrides = {}): GetServerSidePropsContext =>
+ ({
+ req: {
+ cookies: {},
+ headers: {
+ host: "cloud.langfuse.com",
+ "x-forwarded-proto": "https",
+ },
+ },
+ res: {},
+ resolvedUrl: "/demo",
+ ...overrides,
+ }) as unknown as GetServerSidePropsContext;
+
+describe("demo redirect page", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockEnv.env.AUTH_DISABLE_SIGNUP = undefined;
+ mockEnv.env.NEXT_PUBLIC_DEMO_ORG_ID = "demo-org";
+ mockEnv.env.NEXT_PUBLIC_DEMO_PROJECT_ID = "demo-project";
+ mockEnv.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "EU";
+ mockEnv.env.NEXT_PUBLIC_SIGN_UP_DISABLED = "false";
+ prismaMock.project.findUnique.mockResolvedValue({
+ id: "demo-project",
+ });
+ getServerAuthSessionMock.mockResolvedValue(null);
+ });
+
+ it("redirects authenticated users with demo project access to the configured regional demo project", async () => {
+ getServerAuthSessionMock.mockResolvedValue({
+ user: {
+ id: "user-1",
+ organizations: [
+ {
+ projects: [{ id: "demo-project" }],
+ },
+ ],
+ },
+ });
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/project/demo-project/traces",
+ permanent: false,
+ },
+ });
+ expect(prismaMock.project.findUnique).toHaveBeenCalledWith({
+ where: {
+ orgId: "demo-org",
+ id: "demo-project",
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ });
+ });
+
+ it("falls back home for authenticated users without demo project access", async () => {
+ getServerAuthSessionMock.mockResolvedValue({
+ user: {
+ id: "user-1",
+ organizations: [
+ {
+ projects: [{ id: "other-project" }],
+ },
+ ],
+ },
+ });
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ });
+
+ it("falls back home when the session has no database user", async () => {
+ getServerAuthSessionMock.mockResolvedValue({
+ user: null,
+ });
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ });
+
+ it("redirects unauthenticated users to sign up with the demo target", async () => {
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: `/auth/sign-up?targetPath=${encodeURIComponent("/demo")}`,
+ permanent: false,
+ },
+ });
+ expect(prismaMock.project.findUnique).toHaveBeenCalled();
+ });
+
+ it("redirects authenticated users from demo subpaths to the same demo project subpath", async () => {
+ getServerAuthSessionMock.mockResolvedValue({
+ user: {
+ id: "user-1",
+ organizations: [
+ {
+ projects: [{ id: "demo-project" }],
+ },
+ ],
+ },
+ });
+
+ await expect(
+ getDemoServerSideProps(
+ makeCtx({
+ resolvedUrl: "/demo/datasets/dataset-1/items?foo=bar",
+ }),
+ ),
+ ).resolves.toEqual({
+ redirect: {
+ destination: "/project/demo-project/datasets/dataset-1/items?foo=bar",
+ permanent: false,
+ },
+ });
+ });
+
+ it("redirects unauthenticated users to sign up with the demo subpath target", async () => {
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ await expect(
+ getDemoServerSideProps(
+ makeCtx({
+ resolvedUrl: "/demo/datasets/dataset-1/items?foo=bar",
+ }),
+ ),
+ ).resolves.toEqual({
+ redirect: {
+ destination: `/auth/sign-up?targetPath=${encodeURIComponent(
+ "/demo/datasets/dataset-1/items?foo=bar",
+ )}`,
+ permanent: false,
+ },
+ });
+ });
+
+ it("redirects unauthenticated users to sign in when sign-up is disabled", async () => {
+ mockEnv.env.AUTH_DISABLE_SIGNUP = "true";
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: `/auth/sign-in?targetPath=${encodeURIComponent("/demo")}`,
+ permanent: false,
+ },
+ });
+ });
+
+ it("redirects unauthenticated users to sign in with the demo subpath target when sign-up is disabled", async () => {
+ mockEnv.env.AUTH_DISABLE_SIGNUP = "true";
+ getServerAuthSessionMock.mockResolvedValue(null);
+
+ await expect(
+ getDemoServerSideProps(
+ makeCtx({
+ resolvedUrl: "/demo/datasets/dataset-1/items?foo=bar",
+ }),
+ ),
+ ).resolves.toEqual({
+ redirect: {
+ destination: `/auth/sign-in?targetPath=${encodeURIComponent(
+ "/demo/datasets/dataset-1/items?foo=bar",
+ )}`,
+ permanent: false,
+ },
+ });
+ });
+
+ it("falls back to home when no demo project is configured", async () => {
+ mockEnv.env.NEXT_PUBLIC_DEMO_PROJECT_ID = undefined;
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ expect(getServerAuthSessionMock).not.toHaveBeenCalled();
+ expect(prismaMock.project.findUnique).not.toHaveBeenCalled();
+ });
+
+ it("falls back to home when the deployment is not Langfuse Cloud", async () => {
+ mockEnv.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ expect(getServerAuthSessionMock).not.toHaveBeenCalled();
+ expect(prismaMock.project.findUnique).not.toHaveBeenCalled();
+ });
+
+ it("falls back to home when no demo organization is configured", async () => {
+ mockEnv.env.NEXT_PUBLIC_DEMO_ORG_ID = undefined;
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ expect(getServerAuthSessionMock).not.toHaveBeenCalled();
+ expect(prismaMock.project.findUnique).not.toHaveBeenCalled();
+ });
+
+ it("falls back to home when the configured demo project does not exist", async () => {
+ getServerAuthSessionMock.mockResolvedValue({
+ user: {
+ id: "user-1",
+ organizations: [
+ {
+ projects: [{ id: "demo-project" }],
+ },
+ ],
+ },
+ });
+ prismaMock.project.findUnique.mockResolvedValue(null);
+
+ await expect(getDemoServerSideProps(makeCtx())).resolves.toEqual({
+ redirect: {
+ destination: "/",
+ permanent: false,
+ },
+ });
+ });
+});
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
index 810d6390ad..48c0a44db8 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.clienttest.tsx
@@ -1,13 +1,30 @@
-import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const { mutateAsyncMock, signInMock, routerPushMock, useSessionMock } =
- vi.hoisted(() => ({
- mutateAsyncMock: vi.fn(),
- signInMock: vi.fn(),
- routerPushMock: vi.fn(),
- useSessionMock: vi.fn(),
- }));
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const {
+ mutateAsyncMock,
+ signInMock,
+ routerPushMock,
+ routerState,
+ useLangfuseCloudRegionMock,
+ useSessionMock,
+} = vi.hoisted(() => ({
+ mutateAsyncMock: vi.fn(),
+ signInMock: vi.fn(),
+ routerPushMock: vi.fn(),
+ routerState: {
+ isReady: true,
+ query: {} as Record<string, string>,
+ },
+ useLangfuseCloudRegionMock: vi.fn(),
+ useSessionMock: vi.fn(),
+}));
vi.mock("next-auth/react", () => ({
signIn: signInMock,
@@ -17,7 +34,8 @@ vi.mock("next-auth/react", () => ({
vi.mock("next/router", () => ({
useRouter: () => ({
push: routerPushMock,
- query: {},
+ query: routerState.query,
+ isReady: routerState.isReady,
}),
}));
@@ -39,10 +57,7 @@ vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({
}));
vi.mock("@/src/features/organizations/hooks", () => ({
- useLangfuseCloudRegion: () => ({
- isLangfuseCloud: false,
- region: undefined,
- }),
+ useLangfuseCloudRegion: () => useLangfuseCloudRegionMock(),
}));
vi.mock(
@@ -64,13 +79,53 @@ vi.mock(
import { ResetPasswordPage } from "@/src/features/auth-credentials/components/ResetPasswordPage";
+const submitPasswordForm = ({
+ code,
+ passwordLabel,
+ confirmPasswordLabel,
+ submitLabel,
+}: {
+ code: string;
+ passwordLabel: string;
+ confirmPasswordLabel: string;
+ submitLabel: string;
+}) => {
+ fireEvent.change(screen.getByLabelText("Verification code"), {
+ target: { value: code },
+ });
+ fireEvent.change(screen.getByLabelText(passwordLabel), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.change(screen.getByLabelText(confirmPasswordLabel), {
+ target: { value: "Newpass1!" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: submitLabel }));
+};
+
+const flushPasswordSubmit = async () => {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+};
+
describe("ResetPasswordPage re-authentication", () => {
beforeEach(() => {
vi.clearAllMocks();
+ routerState.isReady = true;
+ routerState.query = {};
+ useLangfuseCloudRegionMock.mockReturnValue({
+ isLangfuseCloud: false,
+ region: undefined,
+ });
mutateAsyncMock.mockResolvedValue({ success: true });
signInMock.mockResolvedValue({ ok: true });
});
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
it("re-authenticates after password update while already signed in", async () => {
useSessionMock.mockReturnValue({
status: "authenticated",
@@ -96,16 +151,12 @@ describe("ResetPasswordPage re-authentication", () => {
expect(screen.getByLabelText("Verification code")).toBeTruthy();
});
- fireEvent.change(screen.getByLabelText("Verification code"), {
- target: { value: "123456" },
- });
- fireEvent.change(screen.getByLabelText("New Password"), {
- target: { value: "Newpass1!" },
+ submitPasswordForm({
+ code: "123456",
+ passwordLabel: "New Password",
+ confirmPasswordLabel: "Confirm New Password",
+ submitLabel: "Update Password",
});
- fireEvent.change(screen.getByLabelText("Confirm New Password"), {
- target: { value: "Newpass1!" },
- });
- fireEvent.click(screen.getByRole("button", { name: "Update Password" }));
await waitFor(() => {
expect(mutateAsyncMock).toHaveBeenCalledWith({
@@ -144,16 +195,12 @@ describe("ResetPasswordPage re-authentication", () => {
expect(screen.getByLabelText("Verification code")).toBeTruthy();
});
- fireEvent.change(screen.getByLabelText("Verification code"), {
- target: { value: "654321" },
- });
- fireEvent.change(screen.getByLabelText("Password"), {
- target: { value: "Newpass1!" },
+ submitPasswordForm({
+ code: "654321",
+ passwordLabel: "Password",
+ confirmPasswordLabel: "Confirm Password",
+ submitLabel: "Set password",
});
- fireEvent.change(screen.getByLabelText("Confirm Password"), {
- target: { value: "Newpass1!" },
- });
- fireEvent.click(screen.getByRole("button", { name: "Set password" }));
await waitFor(() => {
expect(signInMock).toHaveBeenCalledWith("credentials", {
@@ -163,4 +210,43 @@ describe("ResetPasswordPage re-authentication", () => {
});
});
});
+
+ it("routes initial Cloud password setup through onboarding with the demo target", async () => {
+ vi.useFakeTimers();
+ routerState.query = {
+ targetPath: "/demo/datasets/dataset-1/items?foo=bar",
+ };
+ useLangfuseCloudRegionMock.mockReturnValue({
+ isLangfuseCloud: true,
+ region: "EU",
+ });
+ useSessionMock.mockReturnValue({
+ status: "unauthenticated",
+ data: null,
+ });
+
+ render(
+ <ResetPasswordPage
+ passwordResetAvailable
+ initialEmail="[email protected]"
+ intent="setup"
+ />,
+ );
+
+ submitPasswordForm({
+ code: "654321",
+ passwordLabel: "Password",
+ confirmPasswordLabel: "Confirm Password",
+ submitLabel: "Set password",
+ });
+
+ await flushPasswordSubmit();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000);
+ });
+
+ expect(routerPushMock).toHaveBeenCalledWith(
+ "/onboarding?targetPath=%2Fdemo%2Fdatasets%2Fdataset-1%2Fitems%3Ffoo%3Dbar",
+ );
+ });
});
diff --git a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
index c8d0338f85..fea14c21d1 100644
--- a/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
+++ b/web/src/features/auth-credentials/components/ResetPasswordPage.tsx
@@ -27,6 +27,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { passwordSchema } from "@/src/features/auth";
import { useLangfuseCloudRegion } from "@/src/features/organizations";
import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials/lib/credentialsUtils";
+import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";
const resetPasswordSchema = z
.object({
@@ -64,6 +65,13 @@ export function ResetPasswordPage({
const isSetMode =
intent === "setup" || session.data?.user?.hasPassword === false;
+ const setupTargetPath =
+ isSetMode && router.isReady
+ ? getDemoTargetPath(router.query.targetPath)
+ : undefined;
+ const setupPasswordPath = setupTargetPath
+ ? `/auth/setup-password?targetPath=${encodeURIComponent(setupTargetPath)}`
+ : "/auth/setup-password";
const mutResetPassword = api.credentials.resetPassword.useMutation();
const effectiveEmail = session.data?.user?.email ?? email;
@@ -112,8 +120,12 @@ export function ResetPasswordPage({
sessionStorage.removeItem(PASSWORD_SETUP_EMAIL_STORAGE_KEY);
}
- let target =
- isSetMode && isLangfuseCloud && region !== "DEV" ? "/onboarding" : "/";
+ let target = setupTargetPath ?? "/";
+ if (isSetMode && isLangfuseCloud && region !== "DEV") {
+ target = setupTargetPath
+ ? `/onboarding?targetPath=${encodeURIComponent(setupTargetPath)}`
+ : "/onboarding";
+ }
// A password update revokes every existing JWT, including this
// browser's, so the current session always has to be re-established.
const signInResult = await signIn("credentials", {
@@ -281,9 +293,7 @@ export function ResetPasswordPage({
</div>
<RequestResetPasswordEmailButton
email={effectiveEmail}
- callbackUrl={
- isSetMode ? "/auth/setup-password" : undefined
- }
+ callbackUrl={isSetMode ? setupPasswordPath : undefined}
onEmailSent={() => setCodeRequested(true)}
label="Send another code"
/>
@@ -291,7 +301,7 @@ export function ResetPasswordPage({
) : (
<RequestResetPasswordEmailButton
email={effectiveEmail}
- callbackUrl={isSetMode ? "/auth/setup-password" : undefined}
+ callbackUrl={isSetMode ? setupPasswordPath : undefined}
onEmailSent={() => setCodeRequested(true)}
/>
)}
diff --git a/web/src/features/auth/SignInPage.tsx b/web/src/features/auth/SignInPage.tsx
index 2b3e8255fd..72df89e696 100644
--- a/web/src/features/auth/SignInPage.tsx
+++ b/web/src/features/auth/SignInPage.tsx
@@ -137,11 +137,13 @@ type NextAuthProvider = NonNullable<Parameters<typeof signIn>[0]>;
export function SSOButtons({
authProviders,
action = "sign in",
+ callbackUrl,
lastUsedMethod,
onProviderSelect,
}: {
authProviders: PageProps["authProviders"];
action?: string;
+ callbackUrl?: string;
lastUsedMethod?: NextAuthProvider | null;
onProviderSelect?: (provider: NextAuthProvider) => void;
}) {
@@ -154,6 +156,7 @@ export function SSOButtons({
([name, enabled]) => enabled && name !== "sso", // sso is just a flag, not an actual provider
);
const hasMultipleAuthMethods = availableProviders.length > 1;
+ const signInOptions = callbackUrl ? { callbackUrl } : undefined;
const handleSignIn = (provider: NextAuthProvider) => {
setProviderSigningIn(provider);
@@ -162,7 +165,7 @@ export function SSOButtons({
// Notify parent component about provider selection
onProviderSelect?.(provider);
- signIn(provider)
+ (signInOptions ? signIn(provider, signInOptions) : signIn(provider))
.then(() => {
// do not reset loadingProvider here, as the page will reload
})
@@ -337,7 +340,7 @@ export function SSOButtons({
onClick={() => {
capture("sign_in:button_click", { provider: "keycloak" });
onProviderSelect?.("keycloak");
- signIn("keycloak");
+ signIn("keycloak", signInOptions);
}}
loading={providerSigningIn === "keycloak"}
showLastUsedBadge={
@@ -353,7 +356,7 @@ export function SSOButtons({
onClick={() => {
capture("sign_in:button_click", { provider: "workos" });
onProviderSelect?.("workos");
- signIn("workos", undefined, {
+ signIn("workos", signInOptions, {
connection: (
authProviders.workos as { connectionId: string }
).connectionId,
@@ -373,7 +376,7 @@ export function SSOButtons({
onClick={() => {
capture("sign_in:button_click", { provider: "workos" });
onProviderSelect?.("workos");
- signIn("workos", undefined, {
+ signIn("workos", signInOptions, {
organization: (
authProviders.workos as { organizationId: string }
).organizationId,
@@ -397,7 +400,7 @@ export function SSOButtons({
if (organization) {
capture("sign_in:button_click", { provider: "workos" });
onProviderSelect?.("workos");
- signIn("workos", undefined, {
+ signIn("workos", signInOptions, {
organization,
});
}
@@ -417,7 +420,7 @@ export function SSOButtons({
if (connection) {
capture("sign_in:button_click", { provider: "workos" });
onProviderSelect?.("workos");
- signIn("workos", undefined, {
+ signIn("workos", signInOptions, {
connection,
});
}
@@ -737,7 +740,10 @@ export default function SignInPage({
// Store the SSO provider as the last used auth method
setLastUsedAuthMethod(providerId as NextAuthProvider);
- signIn(providerId);
+ signIn(
+ providerId,
+ targetPath ? { callbackUrl: targetPath } : undefined,
+ );
return; // stop further execution – page redirect expected
}
@@ -910,6 +916,7 @@ export default function SignInPage({
) : null}
<SSOButtons
authProviders={authProviders}
+ callbackUrl={targetPath}
lastUsedMethod={lastUsedAuthMethod}
onProviderSelect={setLastUsedAuthMethod}
/>
diff --git a/web/src/features/auth/SignUpPage.tsx b/web/src/features/auth/SignUpPage.tsx
index 138364fbd4..e296e79b71 100644
--- a/web/src/features/auth/SignUpPage.tsx
+++ b/web/src/features/auth/SignUpPage.tsx
@@ -35,6 +35,8 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import useLocalStorage from "@/src/components/useLocalStorage";
import { noUrlCheck, StringNoHTMLNonEmpty } from "@langfuse/shared";
import { PASSWORD_SETUP_EMAIL_STORAGE_KEY } from "@/src/features/auth-credentials";
+import { getDemoTargetPath } from "@/src/features/onboarding/lib/demoCallbackRedirect";
+
type NextAuthProvider = NonNullable<Parameters<typeof signIn>[0]>;
// Schema for the verified signup flow (email + name only, no password)
@@ -159,7 +161,10 @@ function StandardSignupFlow({
// Store the SSO provider as the last used auth method
setLastUsedAuthMethod(providerId as NextAuthProvider);
- signIn(providerId);
+ signIn(
+ providerId,
+ targetPath ? { callbackUrl: targetPath } : undefined,
+ );
return; // stop further execution – page redirect expected
}
@@ -208,14 +213,20 @@ function StandardSignupFlow({
return;
}
+ let callbackUrl =
+ targetPath ??
+ (isLangfuseCloud
+ ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`
+ : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`);
+ const demoTargetPath = getDemoTargetPath(targetPath);
+ if (isLangfuseCloud && demoTargetPath) {
+ callbackUrl = `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding?targetPath=${encodeURIComponent(demoTargetPath)}`;
+ }
+
await signIn<"credentials">("credentials", {
email: values.email,
password: values.password,
- callbackUrl:
- targetPath ??
- (isLangfuseCloud
- ? `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/onboarding`
- : `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/`),
+ callbackUrl,
});
} catch {
setFormError("An error occurred. Please try again.");
@@ -305,6 +316,7 @@ function StandardSignupFlow({
<SSOButtons
authProviders={authProviders}
action="sign up"
+ callbackUrl={targetPath}
lastUsedMethod={lastUsedAuthMethod}
onProviderSelect={setLastUsedAuthMethod}
/>
@@ -319,6 +331,14 @@ function VerifiedSignupFlow({
const router = useRouter();
const capture = usePostHogClientCapture();
const emailParam = router.query.email as string | undefined;
+ const queryTargetPath = router.query.targetPath as string | undefined;
+ const targetPath = queryTargetPath
+ ? getSafeRedirectPath(queryTargetPath)
+ : undefined;
+ const demoTargetPath = getDemoTargetPath(targetPath);
+ const setupPasswordPath = demoTargetPath
+ ? `/auth/setup-password?targetPath=${encodeURIComponent(demoTargetPath)}`
+ : "/auth/setup-password";
const [formError, setFormError] = useState<string | null>(null);
const [lastUsedAuthMethod, setLastUsedAuthMethod] =
@@ -360,7 +380,7 @@ function VerifiedSignupFlow({
// Send OTP email via NextAuth email provider
const signInRes = await signIn("email", {
email: values.email,
- callbackUrl: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/auth/setup-password`,
+ callbackUrl: `${env.NEXT_PUBLIC_BASE_PATH ?? ""}${setupPasswordPath}`,
redirect: false,
});
@@ -378,7 +398,7 @@ function VerifiedSignupFlow({
PASSWORD_SETUP_EMAIL_STORAGE_KEY,
values.email.toLowerCase(),
);
- await router.push("/auth/setup-password");
+ await router.push(setupPasswordPath);
} catch {
setFormError("An error occurred. Please try again.");
}
@@ -440,6 +460,7 @@ function VerifiedSignupFlow({
<SSOButtons
authProviders={authProviders}
action="sign up"
+ callbackUrl={targetPath}
lastUsedMethod={lastUsedAuthMethod}
onProviderSelect={setLastUsedAuthMethod}
/>
diff --git a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
index 1ecbd790b7..5b874435d2 100644
--- a/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
+++ b/web/src/features/onboarding/components/ConnectedOnboardingSurvey.tsx
@@ -4,6 +4,7 @@ import { useSession } from "next-auth/react";
import { showErrorToast } from "@/src/features/notifications";
import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";
import { api } from "@/src/utils/api";
+import { getDemoCallbackRedirectPath } from "../lib/demoCallbackRedirect";
import type { SurveyFormData } from "../lib/surveyTypes";
import { OnboardingSurvey } from "./OnboardingSurvey";
@@ -13,6 +14,10 @@ export function ConnectedOnboardingSurvey() {
const utils = api.useUtils();
const onboardingStatus = api.onboarding.status.useQuery();
const completeOnboardingMutation = api.onboarding.complete.useMutation();
+ const queryRedirectPath = router.isReady
+ ? (getDemoCallbackRedirectPath(router.query.targetPath) ??
+ getDemoCallbackRedirectPath(router.query.callbackUrl))
+ : undefined;
const [hasStartedOnboardingCompletion, setHasStartedOnboardingCompletion] =
useState(false);
@@ -35,12 +40,13 @@ export function ConnectedOnboardingSurvey() {
}
: undefined,
);
+ const redirectTo = queryRedirectPath ?? onboardingResult.redirectTo;
utils.onboarding.status.setData(undefined, {
completed: true,
- redirectTo: onboardingResult.redirectTo,
+ redirectTo,
});
await updateSession();
- await router.replace(onboardingResult.redirectTo);
+ await router.replace(redirectTo);
} catch (error) {
setHasStartedOnboardingCompletion(false);
showErrorToast(
@@ -52,6 +58,7 @@ export function ConnectedOnboardingSurvey() {
[
completeOnboardingMutation,
onboardingStatus.data,
+ queryRedirectPath,
router,
updateSession,
utils,
@@ -77,15 +84,21 @@ export function ConnectedOnboardingSurvey() {
);
useEffect(() => {
- if (onboardingStatus.data?.completed && !hasStartedOnboardingCompletion) {
- redirectCompletedOnboarding(onboardingStatus.data.redirectTo).catch(
- () => undefined,
- );
+ if (
+ router.isReady &&
+ onboardingStatus.data?.completed &&
+ !hasStartedOnboardingCompletion
+ ) {
+ redirectCompletedOnboarding(
+ queryRedirectPath ?? onboardingStatus.data.redirectTo,
+ ).catch(() => undefined);
}
}, [
hasStartedOnboardingCompletion,
onboardingStatus.data,
+ queryRedirectPath,
redirectCompletedOnboarding,
+ router.isReady,
]);
const onSubmit = useCallback(
@@ -99,6 +112,7 @@ export function ConnectedOnboardingSurvey() {
hasStartedOnboardingCompletion ||
isFinishingOnboarding ||
isRedirectingCompletedOnboarding ||
+ !router.isReady ||
onboardingStatus.isLoading ||
onboardingStatus.data?.completed === true;
diff --git a/web/src/features/onboarding/lib/demoCallbackRedirect.ts b/web/src/features/onboarding/lib/demoCallbackRedirect.ts
new file mode 100644
index 0000000000..7dabe74e79
--- /dev/null
+++ b/web/src/features/onboarding/lib/demoCallbackRedirect.ts
@@ -0,0 +1,32 @@
+import { getSafeRedirectPath, stripBasePath } from "@/src/utils/redirect";
+
+const getCallbackPath = (url: string): string | null => {
+ if (typeof window === "undefined") return null;
+ if (!/^(\/|https?:\/\/)/i.test(url)) return null;
+
+ try {
+ const parsedUrl = new URL(url, window.location.origin);
+ if (parsedUrl.origin !== window.location.origin) return null;
+ return `${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;
+ } catch {
+ return null;
+ }
+};
+
+export const getDemoTargetPath = (value: unknown): string | undefined => {
+ if (typeof value !== "string") return undefined;
+ const redirectPath = stripBasePath(getSafeRedirectPath(value));
+ const pathname = new URL(redirectPath, "https://langfuse.invalid").pathname;
+ return pathname === "/demo" || pathname.startsWith("/demo/")
+ ? redirectPath
+ : undefined;
+};
+
+export const getDemoCallbackRedirectPath = (
+ value: unknown,
+): string | undefined => {
+ if (typeof value !== "string") return undefined;
+ const callbackPath = getCallbackPath(value);
+ if (!callbackPath) return undefined;
+ return getDemoTargetPath(callbackPath);
+};
diff --git a/web/src/pages/demo/[[...path]].tsx b/web/src/pages/demo/[[...path]].tsx
new file mode 100644
index 0000000000..89e3a2fc3e
--- /dev/null
+++ b/web/src/pages/demo/[[...path]].tsx
@@ -0,0 +1,100 @@
+import { type GetServerSideProps, type GetServerSidePropsResult } from "next";
+
+import { env } from "@/src/env.mjs";
+import { getServerAuthSession } from "@/src/server/auth";
+import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
+import { prisma } from "@langfuse/shared/src/db";
+
+const DemoRedirectPage = () => null;
+
+export default DemoRedirectPage;
+
+export const getServerSideProps: GetServerSideProps = async (ctx) => {
+ const demoProject =
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
+ env.NEXT_PUBLIC_DEMO_ORG_ID &&
+ env.NEXT_PUBLIC_DEMO_PROJECT_ID
+ ? await prisma.project.findUnique({
+ where: {
+ orgId: env.NEXT_PUBLIC_DEMO_ORG_ID,
+ id: env.NEXT_PUBLIC_DEMO_PROJECT_ID,
+ deletedAt: null,
+ },
+ select: {
+ id: true,
+ },
+ })
+ : null;
+
+ if (!demoProject) {
+ return redirect("/");
+ }
+
+ const { demoTargetPath, demoProjectPath } = getDemoRedirectPaths({
+ resolvedUrl: ctx.resolvedUrl,
+ projectId: demoProject.id,
+ });
+ const session = await getServerAuthSession({ req: ctx.req, res: ctx.res });
+
+ if (isProjectMemberOrAdmin(session?.user, demoProject.id)) {
+ return redirect(demoProjectPath);
+ }
+
+ if (session) {
+ return redirect("/");
+ }
+
+ const authPath =
+ env.AUTH_DISABLE_SIGNUP === "true" ||
+ env.NEXT_PUBLIC_SIGN_UP_DISABLED === "true"
+ ? "/auth/sign-in"
+ : "/auth/sign-up";
+
+ return redirect(
+ `${authPath}?targetPath=${encodeURIComponent(demoTargetPath)}`,
+ );
+};
+
+const redirect = (destination: string): GetServerSidePropsResult<never> => ({
+ redirect: { destination, permanent: false },
+});
+
+function getDemoRedirectPaths({
+ resolvedUrl,
+ projectId,
+}: {
+ resolvedUrl: string;
+ projectId: string;
+}) {
+ const encodedProjectId = encodeURIComponent(projectId);
+
+ try {
+ const url = new URL(resolvedUrl, "https://langfuse.invalid");
+
+ if (url.pathname.startsWith("/demo/")) {
+ const demoSuffix = url.pathname.slice("/demo".length);
+ const pathSuffix = `${url.search}${url.hash}`;
+
+ return {
+ demoTargetPath: `${url.pathname}${pathSuffix}`,
+ demoProjectPath: `/project/${encodedProjectId}${demoSuffix}${pathSuffix}`,
+ };
+ }
+
+ if (url.pathname === "/demo") {
+ const pathSuffix = `${url.search}${url.hash}`;
+
+ return {
+ demoTargetPath: `/demo${pathSuffix}`,
+ demoProjectPath: `/project/${encodedProjectId}/traces${pathSuffix}`,
+ };
+ }
+ } catch {
+ // Fall through to the stable default below.
+ }
+
+ return {
+ demoTargetPath: "/demo",
+ demoProjectPath: `/project/${encodedProjectId}/traces`,
+ };
+}