React Auth (useAuth)
Login, register, logout, and social login with cilantro-react
React Auth (useAuth)
useAuth() gives you authentication state and actions: user, JWT, login, register, logout, and (optionally) loginWithSocial for Google/Apple/Discord.
useAuth
import { useAuth } from 'cilantro-react';
function MyComponent() {
const {
user,
jwt,
isLoading,
isAuthenticated,
login,
loginWithSocial,
register,
logout,
clearSessionDueToAuthError,
} = useAuth();
const handleLogin = async () => {
await login({ usernameOrEmail: 'user@example.com', password: 'password123' });
};
const handleRegister = async () => {
await register('johndoe', 'john@example.com', 'password123');
};
return (
<div>
{isLoading && <p>Loading...</p>}
{isAuthenticated ? (
<>
<p>Hello, {user?.username}</p>
<button onClick={logout}>Logout</button>
</>
) : (
<button onClick={handleLogin}>Login</button>
)}
</div>
);
}
Returns (UseAuthResult)
| Property | Type | Description |
|---|---|---|
| user | User | null | Current user (username, email, userType) |
| jwt | string | null | JWT token (null when not authenticated). Prefer this name. |
| token | string | null | Alias for jwt |
| isLoading | boolean | True while restoring session from storage |
| isAuthenticated | boolean | True when user has valid JWT |
| login | (params) => Promise<void> | Log in with usernameOrEmail + password; throws on error |
| loginWithSocial | (params: SocialLoginParams) => Promise<void> | Sign in with Google/Apple (id_token) or Discord (access_token) |
| register | (username, email, password, isActive?) => Promise<void> | Register and auto-login |
| logout | () => void | Clear session and token |
| clearSessionDueToAuthError | () => void | Clear session when API returns 401/403 |
Social login (SocialLoginButtons)
Standalone buttons for Google, Apple, and Discord. Google and Apple use id_token; Discord uses access_token (or the built-in redirect flow).
- Google: Built-in when
socialAuth.googleClientIdis set on CilantroProvider, or provideonGoogleSignInto return the Googleid_token. - Apple: Set
showAppleand provideonAppleSignInthat returns the Appleid_token. - Discord: Either set
socialAuth.discordRedirectUrion CilantroProvider andshowDiscord(built-in redirect), or provideonDiscordSignInthat returns the Discord OAuthaccess_token.
import { SocialLoginButtons } from 'cilantro-react';
<SocialLoginButtons
showGoogle
showApple
showDiscord
onAppleSignIn={async () => (await getAppleIdToken())}
onSuccess={() => router.push('/dashboard')}
showDivider
/>
Discord callback page
When using built-in Discord redirect, on the route that matches your discordRedirectUri, call setAuthFromFragment to complete login:
import { setAuthFromFragment } from 'cilantro-sdk/auth';
function AuthCallbackPage() {
useEffect(() => {
const tokens = setAuthFromFragment({ clearHash: true });
if (tokens) {
router.replace('/dashboard');
}
}, []);
return <div>Signing you in...</div>;
}
LoginForm component
Prebuilt login form with optional Google/Apple and redirect:
import { LoginForm } from 'cilantro-react';
<LoginForm
onSuccess={() => console.log('Logged in!')}
onError={(err) => console.error(err.message)}
redirectAfterSuccess="/dashboard"
onRedirect={(path) => router.replace(path)}
enableGoogleSignIn
onGoogleSignIn={async () => (await getGoogleIdToken())}
title="Welcome back"
submitLabel="Sign in"
renderSwitchToRegister={() => <a href="/register">Create account</a>}
/>
AuthGuard
Protect content behind authentication; shows fallback (default: LoginForm) when not authenticated:
import { AuthGuard } from 'cilantro-react';
<AuthGuard>
<ProtectedContent />
</AuthGuard>