Open source CapCut alternative.
TypeScript
fix(site): hold the session until hydration
David Leed291a3f6741
diff --git a/site/eslint.config.mjs b/site/eslint.config.mjsindex f4b2b000..29d9757c 100644--- a/site/eslint.config.mjs+++ b/site/eslint.config.mjs@@ -50,6 +50,18 @@ const eslintConfig = defineConfig([],},},+ {+ // The session a component renders comes through the hook that keeps the+ // first client render equal to the server's HTML (lib/auth-client.ts).+ files: ["src/**/*.ts", "src/**/*.tsx"],+ ignores: ["src/lib/auth-client.ts"],+ rules: {+ "no-restricted-properties": [+ "error",+ { object: "authClient", property: "useSession", message: "Use useSession from @/lib/auth-client; it renders the server's state until hydration." },+ ],+ },+ },{// The packages are standalone: each must build for any host, so none// reaches into the app's source or aliases.diff --git a/site/src/app/[locale]/cut/app/(home)/onboarding/page.tsx b/site/src/app/[locale]/cut/app/(home)/onboarding/page.tsxindex 8e2abb05..56c798e2 100644--- a/site/src/app/[locale]/cut/app/(home)/onboarding/page.tsx+++ b/site/src/app/[locale]/cut/app/(home)/onboarding/page.tsx@@ -8,7 +8,7 @@ import { SessionGate } from "@/cut/components/SessionGate";import { cloudBackend } from "@/cut/lib/backend/cloud";import { CUT_APP_BASE } from "@/cut/lib/nav";import { starterProjectId } from "@/cut/lib/starter";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";// The welcome sequence's own address. The sequence is a full-window overlay// mounted in the app shell that reads this address itself and opens from its@@ -20,7 +20,7 @@ import { authClient } from "@/lib/auth-client";// home, the same thing that's behind the sequence everywhere else.export default function OnboardingPage() {const router = useRouter();- const { data: session } = authClient.useSession();+ const { data: session } = useSession();const userId = session?.user.id;const sent = useRef(false);diff --git a/site/src/app/[locale]/cut/s/[token]/SharedProjectView.tsx b/site/src/app/[locale]/cut/s/[token]/SharedProjectView.tsxindex 12233703..7f508009 100644--- a/site/src/app/[locale]/cut/s/[token]/SharedProjectView.tsx+++ b/site/src/app/[locale]/cut/s/[token]/SharedProjectView.tsx@@ -14,7 +14,7 @@ import { bindSharedBackend } from "@/cut/lib/backend/shared";import { holdThreadsInMemory } from "@/cut/lib/chatThreads";import { useEditor } from "@/cut/lib/store";import type { ShareFeatures } from "@/cut/lib/types";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";// The read-only share view. This route sits beside the app subtree on purpose:// /cut/app is session-gated (RequireSession) and engine-gated (ConnectGate),@@ -35,7 +35,7 @@ export function SharedProject() {const t = useTranslations("share.view");const untitled = t("untitled");const [gate, setGate] = useState<Gate>({ state: "loading" });- const { data: session } = authClient.useSession();+ const { data: session } = useSession();const narrow = useIsNarrowAtOpen();useEffect(() => {diff --git a/site/src/app/_components/landing/TopNav.tsx b/site/src/app/_components/landing/TopNav.tsxindex bfbaf450..e1debd89 100644--- a/site/src/app/_components/landing/TopNav.tsx+++ b/site/src/app/_components/landing/TopNav.tsx@@ -6,7 +6,7 @@ import { useTranslations } from "next-intl";import { useEffect, useState } from "react";import { PillButton } from "@/app/_components/landing/LandingPrimitives";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";import { cn } from "@/lib/utils";type Props = {@@ -38,7 +38,7 @@ export function TopNav({// right cluster collapses to a single white button into the product. During the// initial (pending) client render `session` is null, which matches the static// server HTML, so the signed-out cluster shows first and swaps in on resolve.- const { data: session } = authClient.useSession();+ const { data: session } = useSession();const isSignedIn = Boolean(session);// The header is sticky and transparent over the hero; once the page scrolls adiff --git a/site/src/app/_components/landing/useAppEntryHref.ts b/site/src/app/_components/landing/useAppEntryHref.tsindex 93482b63..bf47f365 100644--- a/site/src/app/_components/landing/useAppEntryHref.ts+++ b/site/src/app/_components/landing/useAppEntryHref.ts@@ -1,6 +1,6 @@"use client";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";// AuthScreen's post-auth fallback when no callbackURL rides the query string.// Targets equal to it need no param, keeping the common auth URLs clean.@@ -24,7 +24,7 @@ export function authHrefFor(// session is unknown, matching the static server HTML, so CTAs render the app// target first and swap to the sign-in link once a signed-out session resolves.export function useAppEntryHref(): (appTarget: string) => string {- const { data: session, isPending } = authClient.useSession();+ const { data: session, isPending } = useSession();return (appTarget: string) =>isPending || session ? appTarget : authHrefFor("/sign-in", appTarget);}diff --git a/site/src/cut/components/NavUser.tsx b/site/src/cut/components/NavUser.tsxindex 5fc1db1e..2ebd618c 100644--- a/site/src/cut/components/NavUser.tsx+++ b/site/src/cut/components/NavUser.tsx@@ -26,7 +26,7 @@ import { connectToEngine } from "@/cut/lib/connect";import { cutInstallHref } from "@/cut/lib/install";import { openOnboarding } from "@/cut/lib/onboarding";import { useCutBase } from "@/cut/lib/nav";-import { authClient } from "@/lib/auth-client";+import { authClient, useSession } from "@/lib/auth-client";import { useAccountProfile, visibleName } from "@/queries/accountProfile";// Signed-in user row pinned to the sidebar bottom; the whole row opens the@@ -44,7 +44,7 @@ export function NavUser() {const router = useRouter();const base = useCutBase();const user = useEngineUser();- const { data: session } = authClient.useSession();+ const { data: session } = useSession();// Mounted above the account check so the hook order is stable; it stays idle// until there's an account to read a profile for.const { data: profile, isPending } = useAccountProfile({ enabled: Boolean(user) });diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 77151cf1..405e33ba 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -13,7 +13,7 @@ import {setEngineUser,} from "@/cut/lib/api";import { reportExposures, useAppLoaded } from "@/lib/analytics";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";import { useAccountConfig } from "@/queries/accountConfig";import { useNoteOutboxSync } from "@/cut/hooks/useNoteOutboxSync";@@ -25,7 +25,7 @@ import { useNoteOutboxSync } from "@/cut/hooks/useNoteOutboxSync";// It binds the account id; SessionGate, one level in, is what holds the app// until the id lands, because every engine URL carries it.export function RequireSession({ children }: { children: ReactNode }) {- const { data: session, isPending, refetch } = authClient.useSession();+ const { data: session, isPending, refetch } = useSession();useNoteOutboxSync();const signedOut = !isPending && !session;diff --git a/site/src/cut/components/ViewerTopBar.tsx b/site/src/cut/components/ViewerTopBar.tsxindex d936f4ef..762053e8 100644--- a/site/src/cut/components/ViewerTopBar.tsx+++ b/site/src/cut/components/ViewerTopBar.tsx@@ -13,7 +13,7 @@ import { projectHref, useCutBase } from "@/cut/lib/nav";import { OperationError, operationFailure } from "@/cut/lib/operationFailure";import { useEditor } from "@/cut/lib/store";import { errorFromBody } from "@/cut/lib/userError";-import { authClient } from "@/lib/auth-client";+import { useSession } from "@/lib/auth-client";// Chrome for the read-only share view: logo, project name, a "View only"// chip, and the viewer's two actions — open the shared chat (when the share@@ -27,7 +27,7 @@ export function ViewerTopBar({ chatStatus }: { chatStatus: ChatStatus }) {const base = useCutBase();const projectName = useEditor((s) => s.projectName);const chatShared = useEditor((s) => s.sharedFeatures?.chat === true);- const { data: session } = authClient.useSession();+ const { data: session } = useSession();const [copying, setCopying] = useState(false);const [copyError, setCopyError] = useState<string | null>(null);diff --git a/site/src/lib/auth-client.test.tsx b/site/src/lib/auth-client.test.tsxnew file mode 100644index 00000000..09054747--- /dev/null+++ b/site/src/lib/auth-client.test.tsx@@ -0,0 +1,24 @@+import { describe, expect, test } from "bun:test";+import { createElement } from "react";+import { renderToString } from "react-dom/server";++import { stubModule } from "@/lib/testing/stubModule";++// A visitor whose session check came back signed out before the page hydrated.+await stubModule("better-auth/react", import.meta.url, {+ createAuthClient: () => ({ useSession: () => ({ data: null, isPending: false }) }),+} as never);+const { useSession } = await import("./auth-client");++function Status() {+ const { data, isPending } = useSession();+ return createElement("span", null, isPending ? "pending" : data ? "signed in" : "signed out");+}++describe("useSession", () => {+ test("renders pending first, the way the static page was served", () => {+ // Hydration renders against the server snapshot; the resolved session+ // lands in the commit after.+ expect(renderToString(createElement(Status))).toBe("<span>pending</span>");+ });+});diff --git a/site/src/lib/auth-client.ts b/site/src/lib/auth-client.tsindex 2f75fd48..3bb3ff0b 100644--- a/site/src/lib/auth-client.ts+++ b/site/src/lib/auth-client.ts@@ -1,5 +1,22 @@"use client";import { createAuthClient } from "better-auth/react";+import { useSyncExternalStore } from "react";export const authClient = createAuthClient();++// Nothing to subscribe to: the answer only changes from server to client.+const subscribeNothing = () => () => {};++/**+ * The session as a component renders it. The server knows no session, so its+ * HTML is the pending state, and so is the client's first render: the session+ * check starts with the page and can answer before a section hydrates, which+ * would otherwise render a different tree over the server's (React #418).+ * The resolved session lands in the commit after hydration.+ */+export function useSession(): ReturnType<typeof authClient.useSession> {+ const live = authClient.useSession();+ const hydrated = useSyncExternalStore(subscribeNothing, () => true, () => false);+ return hydrated ? live : { ...live, data: null, isPending: true };+}