BuildBaseBuildBase

Sign In & Sign Out

Handle sign-in, sign-out, and user state in your React app.

useSaaSAuth() is the primary hook for authentication. Call signIn() to redirect to the BuildBase auth portal, signOut() to end the session.

import { useSaaSAuth } from '@buildbase/sdk/react';

function App() {
  const { user, isAuthenticated, signIn, signOut } = useSaaSAuth();

  if (!isAuthenticated) {
    return <button onClick={() => signIn()}>Sign In</button>;
  }

  return (
    <div>
      <p>Welcome, {user?.name}</p>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}

useSaaSAuth() returns

PropertyTypeDescription
userAuthUser or undefinedThe authenticated user: id, name, email, emailVerified, role, org, clientId, image?
sessionAuthSession or nullThe current session: user, sessionId, expires
status'loading' | 'redirecting' | 'authenticated' | 'unauthenticated' | 'authenticating'Session resolution state
isLoadingbooleanTrue while session is resolving
isRedirectingbooleanTrue while redirecting to the auth portal
isAuthenticatedbooleanTrue when signed in
signIn(returnUrl?)functionRedirect to sign-in portal
signOut()functionEnd the session
openWorkspaceSettings(section?)functionOpen workspace settings panel
openCreditStore()functionOpen the credit store
openPlanPicker()functionOpen the plan picker

Conditional rendering

import { WhenAuthenticated, WhenUnauthenticated } from '@buildbase/sdk/react';

function Page() {
  return (
    <>
      <WhenAuthenticated>
        <Dashboard />
      </WhenAuthenticated>
      <WhenUnauthenticated>
        <LoginPage />
      </WhenUnauthenticated>
    </>
  );
}

Handle loading state

The SDK checks the session on first render. Always handle loading:

const { isLoading, isAuthenticated } = useSaaSAuth();

if (isLoading) return <Spinner />;
if (!isAuthenticated) return <SignInPage />;
return <Dashboard />;

Error handling

Auth errors surface through the handleAuthentication callback in your provider config. If the callback throws or the auth code exchange fails, the SDK does not update the session — the user stays unauthenticated.

// In your SaaSOSProvider auth config
auth={{
  clientId: 'your-client-id',
  redirectUrl: '/callback',
  callbacks: {
    getSession: async () => localStorage.getItem('sessionId'),
    onSignOut: async () => localStorage.removeItem('sessionId'),
    handleAuthentication: async (code) => {
      try {
        const res = await fetch('/api/auth/verify', {
          method: 'POST',
          body: JSON.stringify({ code }),
        });
        if (!res.ok) throw new Error('Auth failed');
        const data = await res.json();
        return { sessionId: data.sessionId };
      } catch (error) {
        // Show a toast, redirect to an error page, or log
        console.error('Authentication failed:', error);
        throw error; // Re-throw so the SDK knows auth failed
      }
    },
  },
}}

Common failure scenarios:

  • Network error — the callback fetch fails. Show a retry prompt.
  • Invalid code — the auth code expired or was already used. The user needs to sign in again.
  • Server error — your backend returned a non-200 response. Check server logs.

Preserve return URL

Pass a URL to signIn() to redirect the user back after authentication:

<button onClick={() => signIn('/settings')}>Sign in to view settings</button>

Next Steps