---
updatedAt: 2026-03-26T02:32:35.000Z
agentTools:
  projectIndex: https://docs.onechain.nexus/v1.4/llms.txt
---

# Authentication

# React SDK — Authentication

This page explains how to handle authentication in React using the `useAuth` hook.

## useAuth

```tsx
import { useAuth } from '@nexus-cross/crossx-sdk-react'

function LoginButton() {
  const { signIn, signOut, isAuthenticated, isLoading, error } = useAuth()

  if (isLoading) return <span>Loading...</span>

  return isAuthenticated ? (
    <button onClick={signOut}>Sign Out</button>
  ) : (
    <button onClick={signIn}>
      Sign In
    </button>
  )
}
```

### Return values

| Property           | Type                                    | Description                                    |
| ------------------ | --------------------------------------- | ---------------------------------------------- |
| `isAuthenticated`  | `boolean`                               | Authentication state (reactive via SDK events) |
| `isLoading`        | `boolean`                               | Loading state                                  |
| `error`            | `string \| null`                        | Last error message                             |
| `signIn`           | `() => Promise<AuthResult>`             | Sign in (opens OAuth selector)                 |
| `signInWithCreate` | `() => Promise<SignInWithCreateResult>` | Sign in + auto wallet creation + migration     |
| `signOut`          | `() => Promise<void>`                   | Sign out                                       |

## Login flow

```tsx
// Standard sign in (opens OAuth provider selector)
const { signIn } = useAuth()
await signIn()

// Sign in + auto wallet creation (recommended for new users)
const { signInWithCreate } = useAuth()
const result = await signInWithCreate()
console.log(result.addresses) // [{ address: '0x...', index: 0 }]
```

> `signIn()` does not accept options. It opens the OAuth provider selector modal.
> To specify a provider programmatically, use `sdk.signIn({ provider: 'google' })` via `useCROSSx()`.

## Session handling

`CROSSxProvider` calls `sdk.initialize()` on mount:

* If a stored session exists and is valid, `isAuthenticated` becomes `true` immediately.
* If the session has expired but a refresh token is valid, it is refreshed automatically.
* `isLoading` is `true` while session restoration is in progress.
* Auth state is kept in sync via SDK's `authChanged` event using `useSyncExternalStore`.

## Recommended pattern

```tsx
function App() {
  const { isAuthenticated, isLoading } = useAuth()

  if (isLoading) return <LoadingScreen />
  if (!isAuthenticated) return <LoginScreen />
  return <MainApp />
}
```