🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(auth): make the auth shell safe to prerender (#18541)
Innei2b55c8e7ef0c
diff --git a/src/components/Analytics/LobeAnalyticsProviderWrapper.tsx b/src/components/Analytics/LobeAnalyticsProviderWrapper.tsxindex 17570a7add3..5fbfa051163 100644--- a/src/components/Analytics/LobeAnalyticsProviderWrapper.tsx+++ b/src/components/Analytics/LobeAnalyticsProviderWrapper.tsx@@ -2,46 +2,54 @@ import { type ReactNode } from 'react';import { memo } from 'react';import { LobeAnalyticsProvider } from '@/components/Analytics/LobeAnalyticsProvider';-import type { SPAServerConfig } from '@/types/spaServerConfig';+import type { AnalyticsConfig, SPAServerConfig } from '@/types/spaServerConfig';import { isDev } from '@/utils/env';type Props = {+ analytics?: AnalyticsConfig;children: ReactNode;};-export const LobeAnalyticsProviderWrapper = memo<Props>(({ children }) => {- const serverConfig: SPAServerConfig | undefined = window.__SERVER_CONFIG__;- const analytics = serverConfig?.analyticsConfig;+const readInjectedAnalytics = (): AnalyticsConfig | undefined => {+ if (typeof window === 'undefined') return undefined;- return (- <LobeAnalyticsProvider- ga4Config={{- debug: isDev,- enabled: !!analytics?.google?.measurementId,- gtagConfig: {- debug_mode: isDev,- },- measurementId: analytics?.google?.measurementId ?? '',- }}- postHogConfig={{- debug: analytics?.posthog?.debug ?? false,- enabled: !!analytics?.posthog?.key,- capture_pageview: 'history_change',- host: analytics?.posthog?.host ?? '',- key: analytics?.posthog?.key ?? '',- person_profiles: 'always',- }}- xAdsConfig={{- debug: isDev,- eventIds: analytics?.xAds?.eventIds,- enabled: !!analytics?.xAds?.pixelId,- pixelId: analytics?.xAds?.pixelId ?? '',- purchaseEventId: analytics?.xAds?.purchaseEventId,- }}- >- {children}- </LobeAnalyticsProvider>- );-});+ return (window.__SERVER_CONFIG__ as SPAServerConfig | undefined)?.analyticsConfig;+};++export const LobeAnalyticsProviderWrapper = memo<Props>(+ ({ analytics: analyticsProp, children }) => {+ const analytics = analyticsProp ?? readInjectedAnalytics();++ return (+ <LobeAnalyticsProvider+ ga4Config={{+ debug: isDev,+ enabled: !!analytics?.google?.measurementId,+ gtagConfig: {+ debug_mode: isDev,+ },+ measurementId: analytics?.google?.measurementId ?? '',+ }}+ postHogConfig={{+ debug: analytics?.posthog?.debug ?? false,+ enabled: !!analytics?.posthog?.key,+ capture_pageview: 'history_change',+ host: analytics?.posthog?.host ?? '',+ key: analytics?.posthog?.key ?? '',+ person_profiles: 'always',+ }}+ xAdsConfig={{+ debug: isDev,+ eventIds: analytics?.xAds?.eventIds,+ enabled: !!analytics?.xAds?.pixelId,+ pixelId: analytics?.xAds?.pixelId ?? '',+ purchaseEventId: analytics?.xAds?.purchaseEventId,+ }}+ >+ {children}+ </LobeAnalyticsProvider>+ );+ },+);LobeAnalyticsProviderWrapper.displayName = 'LobeAnalyticsProviderWrapper';diff --git a/src/features/Auth/OAuthGuard.tsx b/src/features/Auth/OAuthGuard.tsxindex 45091a5e0e9..7d0fb4fb7f3 100644--- a/src/features/Auth/OAuthGuard.tsx+++ b/src/features/Auth/OAuthGuard.tsx@@ -3,7 +3,7 @@import { memo, type PropsWithChildren } from 'react';import NotFound from '@/components/404';-import { useAuthServerConfigStore } from '@/features/AuthShell';+import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';const OAuthGuard = memo<PropsWithChildren>(({ children }) => {const enableOIDC = useAuthServerConfigStore((s) => s.enableOIDC);diff --git a/src/features/Auth/ResetPassword/index.tsx b/src/features/Auth/ResetPassword/index.tsxindex 3364c9b1281..81b768783bf 100644--- a/src/features/Auth/ResetPassword/index.tsx+++ b/src/features/Auth/ResetPassword/index.tsx@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';import { Link, Navigate, useNavigate, useSearchParams } from 'react-router';import AuthCard from '@/features/AuthCard';-import { useAuthServerConfigStore } from '@/features/AuthShell';+import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';import { ResetPasswordContent } from './ResetPasswordContent';diff --git a/src/features/Auth/SignIn/SignInEmailStep.tsx b/src/features/Auth/SignIn/SignInEmailStep.tsxindex d0c3dd2bc2c..6684e59822e 100644--- a/src/features/Auth/SignIn/SignInEmailStep.tsx+++ b/src/features/Auth/SignIn/SignInEmailStep.tsx@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';import AuthIcons from '@/components/AuthIcons';import AuthCard from '@/features/AuthCard';-import { AuthAgreement, useAuthAgreement } from '@/features/AuthShell';+import AuthAgreement, { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';const styles = createStaticStyles(({ css, cssVar }) => ({inlineLink: css`diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.tsindex fca6a7cd678..4559f859cc4 100644--- a/src/features/Auth/SignIn/useSignIn.test.ts+++ b/src/features/Auth/SignIn/useSignIn.test.ts@@ -67,7 +67,7 @@ vi.mock('@/business/client/hooks/useBusinessSignin', () => ({let mockEnableBusinessFeatures = false;let mockEnableMagicLink = false;-vi.mock('@/features/AuthShell', () => ({+vi.mock('@/features/AuthShell/AuthServerConfigProvider', () => ({useAuthServerConfigStore: (selector: (s: any) => any) =>selector({serverConfig: {diff --git a/src/features/Auth/SignIn/useSignIn.ts b/src/features/Auth/SignIn/useSignIn.tsindex 3bbf677cd88..5ed6b60a8fe 100644--- a/src/features/Auth/SignIn/useSignIn.ts+++ b/src/features/Auth/SignIn/useSignIn.ts@@ -7,7 +7,7 @@ import { useNavigate, useSearchParams } from 'react-router';import type { CheckUserResponseData } from '@/app/(backend)/api/auth/check-user/route';import type { ResolveUsernameResponseData } from '@/app/(backend)/api/auth/resolve-username/route';import { useBusinessSignin } from '@/business/client/hooks/useBusinessSignin';-import { useAuthServerConfigStore } from '@/features/AuthShell';+import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';import { requestPasswordReset, signIn } from '@/libs/better-auth/auth-client';import { isBuiltinProvider, normalizeProviderId } from '@/libs/better-auth/utils/client';@@ -62,17 +62,21 @@ export const useSignIn = () => {const [email, setEmail] = useState('');const [sentInfo, setSentInfo] = useState<SentEmailInfo | null>(null);const [isSocialOnly, setIsSocialOnly] = useState(false);- const [lastAuthProvider] = useState(() => {- try {- return localStorage.getItem(LAST_AUTH_PROVIDER_KEY);- } catch {- return null;- }- });+ // Read after mount, not during render: this page is prerendered, and a stored+ // provider would make the first client render disagree with the document.+ const [lastAuthProvider, setLastAuthProvider] = useState<string | null>(null);const serverConfigInit = useAuthServerConfigStore((s) => s.serverConfigInit);const oAuthSSOProviders = useAuthServerConfigStore((s) => s.serverConfig.oAuthSSOProviders) || [];const { getAdditionalData, preSocialSigninCheck, ssoProviders } = useBusinessSignin();+ useEffect(() => {+ try {+ setLastAuthProvider(localStorage.getItem(LAST_AUTH_PROVIDER_KEY));+ } catch {+ // Private mode and blocked storage both just mean "no last provider".+ }+ }, []);+useEffect(() => {const emailParam = searchParams.get('email');if (emailParam) form.setFieldValue('email', emailParam);diff --git a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsxindex 0e4c30171ec..266064caabc 100644--- a/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx+++ b/src/features/Auth/SignUp/BetterAuthSignUpForm.tsx@@ -10,7 +10,7 @@ import { useTranslation } from 'react-i18next';import { Link, useNavigate, useSearchParams } from 'react-router';import { AuthCard } from '@/features/AuthCard';-import { AuthAgreement, useAuthAgreement } from '@/features/AuthShell';+import AuthAgreement, { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';import { useSignUp } from './useSignUp';diff --git a/src/features/Auth/SignUp/index.tsx b/src/features/Auth/SignUp/index.tsxindex 0f369c81603..670cdb173e7 100644--- a/src/features/Auth/SignUp/index.tsx+++ b/src/features/Auth/SignUp/index.tsx@@ -2,7 +2,7 @@import { Navigate } from 'react-router';-import { useAuthServerConfigStore } from '@/features/AuthShell';+import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';import BetterAuthSignUpForm from './BetterAuthSignUpForm';diff --git a/src/features/Auth/SignUp/useSignUp.test.ts b/src/features/Auth/SignUp/useSignUp.test.tsindex 4f49ac5d800..bd864e1746c 100644--- a/src/features/Auth/SignUp/useSignUp.test.ts+++ b/src/features/Auth/SignUp/useSignUp.test.ts@@ -39,7 +39,7 @@ vi.mock('@/business/client/hooks/useBusinessSignup', () => ({let mockEnableEmailVerification = false;let mockEnableBusinessFeatures = false;-vi.mock('@/features/AuthShell', () => ({+vi.mock('@/features/AuthShell/AuthServerConfigProvider', () => ({useAuthServerConfigStore: (selector: (s: any) => any) =>selector({serverConfig: {diff --git a/src/features/Auth/SignUp/useSignUp.ts b/src/features/Auth/SignUp/useSignUp.tsindex 354745704a6..4dd666d9ae1 100644--- a/src/features/Auth/SignUp/useSignUp.ts+++ b/src/features/Auth/SignUp/useSignUp.ts@@ -8,7 +8,7 @@ import type { BusinessSignupFomData } from '@/business/client/hooks/useBusinessSimport { useBusinessSignup } from '@/business/client/hooks/useBusinessSignup';import type { AuthFetchOptions } from '@/features/Auth/utils/authFetchOptions';import { withCaptchaToken } from '@/features/Auth/utils/authFetchOptions';-import { useAuthServerConfigStore } from '@/features/AuthShell';+import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';import { signUp } from '@/libs/better-auth/auth-client';import { buildOnboardingRedirectUrl, toAbsoluteAuthCallbackUrl } from '@/utils/onboardingRedirect';diff --git a/src/features/AuthShell/AuthAgreement.tsx b/src/features/AuthShell/AuthAgreement.tsxindex ea77f3c1784..3b488cac61a 100644--- a/src/features/AuthShell/AuthAgreement.tsx+++ b/src/features/AuthShell/AuthAgreement.tsx@@ -2,7 +2,7 @@import { Checkbox, confirmModal, Text } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';-import { memo, useCallback, useState } from 'react';+import { memo, useCallback, useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';import { PRIVACY_URL, TERMS_URL } from '@/const/url';@@ -94,7 +94,13 @@ const AgreementText = memo<AgreementTextProps>(({ i18nKey }) => {export const useAuthAgreement = (requestConfirmation?: RequestAgreementConfirmation) => {const { t } = useTranslation(['auth', 'common']);- const [agreementChecked, setAgreementCheckedState] = useState(readStoredAgreement);+ // Read after mount, not during render — the sign-in page is prerendered and a+ // remembered acceptance would not match the document's unchecked box.+ const [agreementChecked, setAgreementCheckedState] = useState(false);++ useEffect(() => {+ setAgreementCheckedState(readStoredAgreement());+ }, []);const setAgreementChecked = useCallback((checked: boolean) => {setAgreementCheckedState(checked);diff --git a/src/features/AuthShell/AuthServerConfigProvider.tsx b/src/features/AuthShell/AuthServerConfigProvider.tsxindex dba61c6b3a4..d685657c2c7 100644--- a/src/features/AuthShell/AuthServerConfigProvider.tsx+++ b/src/features/AuthShell/AuthServerConfigProvider.tsx@@ -1,5 +1,6 @@'use client';+import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';import type { ReactNode } from 'react';import { createContext, memo, use } from 'react';@@ -31,7 +32,12 @@ export const AuthServerConfigProvider = memo<Props>(enableOIDC: enableOIDC ?? false,featureFlags: featureFlags || {},isMobile,- serverConfig: serverConfig || { aiProvider: {}, telemetry: {} },+ // Baked into the bundle at build time, so it must not wait on injected+ // config — prerendered markup depends on knowing it during the render.+ serverConfig: {+ ...(serverConfig || { aiProvider: {}, telemetry: {} }),+ enableBusinessFeatures: ENABLE_BUSINESS_FEATURES,+ },serverConfigInit: true,}}>