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)

PropertyTypeDescription
userUser | nullCurrent user (username, email, userType)
jwtstring | nullJWT token (null when not authenticated). Prefer this name.
tokenstring | nullAlias for jwt
isLoadingbooleanTrue while restoring session from storage
isAuthenticatedbooleanTrue 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() => voidClear session and token
clearSessionDueToAuthError() => voidClear 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.googleClientId is set on CilantroProvider, or provide onGoogleSignIn to return the Google id_token.
  • Apple: Set showApple and provide onAppleSignIn that returns the Apple id_token.
  • Discord: Either set socialAuth.discordRedirectUri on CilantroProvider and showDiscord (built-in redirect), or provide onDiscordSignIn that returns the Discord OAuth access_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>

Next steps

React Auth (useAuth) | Cilantro Smart Wallet Docs | Cilantro Smart Wallet