# 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.

```tsx
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

| Property                          | Type                                                                                             | Description                                                                                         |
| --------------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| `user`                            | `AuthUser` or `undefined`                                                                        | The authenticated user: `id`, `name`, `email`, `emailVerified`, `role`, `org`, `clientId`, `image?` |
| `session`                         | `AuthSession` or `null`                                                                          | The current session: `user`, `sessionId`, `expires`                                                 |
| `status`                          | `'loading'` \| `'redirecting'` \| `'authenticated'` \| `'unauthenticated'` \| `'authenticating'` | Session resolution state                                                                            |
| `isLoading`                       | `boolean`                                                                                        | True while session is resolving                                                                     |
| `isRedirecting`                   | `boolean`                                                                                        | True while redirecting to the auth portal                                                           |
| `isAuthenticated`                 | `boolean`                                                                                        | True when signed in                                                                                 |
| `signIn(returnUrl?)`              | `function`                                                                                       | Redirect to sign-in portal                                                                          |
| `signOut()`                       | `function`                                                                                       | End the session                                                                                     |
| `openWorkspaceSettings(section?)` | `function`                                                                                       | Open workspace settings panel                                                                       |
| `openCreditStore()`               | `function`                                                                                       | Open the credit store                                                                               |
| `openPlanPicker()`                | `function`                                                                                       | Open the plan picker                                                                                |

## Conditional rendering

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

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

## Handle loading state

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

```tsx
const { isLoading, isAuthenticated } = useSaaSAuth();

if (isLoading) return ;
if (!isAuthenticated) return ;
return ;
```

## 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.

```tsx
// 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:

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

## Next Steps

- [Protected Routes](/authentication/protected-routes) — Guard routes and sections of your app.
