Authentication
React SDK — Authentication
This page explains how to handle authentication in React using the useAuth hook.
useAuth
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
// 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, usesdk.signIn({ provider: 'google' })viauseCROSSx().
Session handling
CROSSxProvider calls sdk.initialize() on mount:
- If a stored session exists and is valid,
isAuthenticatedbecomestrueimmediately. - If the session has expired but a refresh token is valid, it is refreshed automatically.
isLoadingistruewhile session restoration is in progress.- Auth state is kept in sync via SDK's
authChangedevent usinguseSyncExternalStore.
Recommended pattern
function App() {
const { isAuthenticated, isLoading } = useAuth()
if (isLoading) return <LoadingScreen />
if (!isAuthenticated) return <LoginScreen />
return <MainApp />
}Updated 15 days ago