Skip to main content
InsForge provides three levels of flexibility for implementing authentication in your app:

Key Difference from Hosted Auth

AspectHosted AuthCustom Components
Sign-in routeRedirects to https://your-app.region.insforge.app/auth/sign-inRenders your <SignIn /> component
Where auth happensOn hosted pageIn your app
Token managementReturns to your app with tokenSDK handles automatically

How It Works

1. User visits /sign-in route → Renders <SignIn> component

2. User enters credentials → Component calls SDK methods

3. SDK communicates with backend → Returns auth token and user data

4. Component adds token to URL and redirects → SDK auto-detects token from URL

5. Provider automatically updates auth state → Components re-render

6. User sees authenticated UI at destination

Before You Start

Make sure to create an InsForge SDK client and wrap your app in the InsforgeProvider:
src/lib/insforge.ts
import { createClient } from '@insforge/sdk';

export const insforge = createClient({
  baseUrl: import.meta.env.VITE_INSFORGE_BASE_URL,
  anonKey: import.meta.env.VITE_INSFORGE_ANON_KEY,
});
src/main.tsx
import { InsforgeProvider } from '@insforge/react';
import { insforge } from './lib/insforge';
import App from './App';

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <InsforgeProvider client={insforge}>
      <App />
    </InsforgeProvider>
  </StrictMode>
);

Complete Components (with Business Logic)

These components include full authentication logic and work out of the box.

<SignIn />

Complete sign-in component with email/password and OAuth:
import { SignIn } from '@insforge/react';

function SignInPage() {
  return (
    <SignIn
      title="Welcome Back"
      subtitle="Sign in to continue"
      onError={(error) => console.error('Error:', error)}
    />
  );
}
Key Features:
  • Email/password authentication
  • OAuth provider buttons (auto-detected from backend)
  • Email verification flow (when required)
  • Password visibility toggle
  • Error handling & loading states
Props:
PropTypeDescription
titlestringCustom title text
subtitlestringCustom subtitle text
emailLabelstringLabel for email input
emailPlaceholderstringPlaceholder for email input
passwordLabelstringLabel for password input
passwordPlaceholderstringPlaceholder for password input
forgotPasswordTextstringText for forgot password link
forgotPasswordUrlstringURL for forgot password page
submitButtonTextstringText for submit button
loadingButtonTextstringText while loading
signUpTextstringText before sign up link
signUpLinkTextstringText for sign up link
signUpUrlstringURL for sign up page
dividerTextstringText in OAuth divider
onError(error: Error) => voidCallback on error

<SignUp />

Complete sign-up component with password strength validation:
import { SignUp } from '@insforge/react';

function SignUpPage() {
  return (
    <SignUp
      title="Create Account"
      subtitle="Get started with your free account"
      onError={(error) => console.error('Error:', error)}
    />
  );
}
Key Features:
  • Email/password registration
  • Real-time password strength indicator
  • Email verification flow (when required)
  • OAuth provider buttons
  • Form validation based on backend config
Props:
PropTypeDescription
titlestringCustom title text
subtitlestringCustom subtitle text
emailLabelstringLabel for email input
emailPlaceholderstringPlaceholder for email input
passwordLabelstringLabel for password input
passwordPlaceholderstringPlaceholder for password input
submitButtonTextstringText for submit button
loadingButtonTextstringText while loading
signInTextstringText before sign in link
signInLinkTextstringText for sign in link
signInUrlstringURL for sign in page
dividerTextstringText in OAuth divider
onError(error: Error) => voidCallback on error

<UserButton />

User profile dropdown with sign-out and profile management:
import { UserButton } from '@insforge/react';

function Header() {
  return (
    <header>
      <nav>{/* Your navigation */}</nav>
      <UserButton 
        mode="detailed" 
        afterSignOutUrl="/" 
        showProfile={true}
        onProfileError={(error) => console.error('Profile error:', error)}
      />
    </header>
  );
}
Key Features:
  • Avatar with fallback to initials
  • Dropdown menu with Profile and Sign Out options
  • Built-in UserProfileModal integration
  • Auto-positioning (opens upward/downward based on viewport)
Props:
PropTypeDefaultDescription
mode"detailed" | "simple""simple"detailed: avatar + name + email, simple: avatar only
afterSignOutUrlstring"/"Redirect URL after sign out
showProfilebooleantrueShow the Profile menu item
onProfileError(error: string) => void-Callback when profile update fails

<UserProfileModal />

Modal for viewing and editing user profile information:
import { useState } from 'react';
import { UserProfileModal } from '@insforge/react';

function ProfileButton() {
  const [showModal, setShowModal] = useState(false);

  return (
    <>
      <button onClick={() => setShowModal(true)}>Edit Profile</button>
      
      {showModal && (
        <UserProfileModal
          onClose={() => setShowModal(false)}
          onError={(error) => console.error('Profile error:', error)}
        />
      )}
    </>
  );
}
Key Features:
  • Displays user avatar, email, and name
  • Edit mode for updating name
  • Avatar fallback to initials
  • Keyboard support (Escape to close)
  • Portal rendering for proper z-index handling
Props:
PropTypeDescription
onClose() => voidCalled when modal is closed
onError(error: string) => voidCalled when an error occurs

<SignInButton /> / <SignUpButton />

Simple buttons that redirect to hosted auth pages:
import { SignInButton, SignUpButton } from '@insforge/react';

function LandingPage() {
  return (
    <div>
      {/* Default button */}
      <SignInButton />
      <SignUpButton />

      {/* Custom styled button */}
      <SignInButton>
        <button className="my-custom-button">Login</button>
      </SignInButton>
    </div>
  );
}
Props:
PropTypeDescription
childrenReactNodeCustom button element (wraps with click handler)
classNamestringCSS class for default button

<SignOutButton />

Simple button that signs out the current user:
import { SignOutButton } from '@insforge/react';

function Header() {
  return (
    <SignOutButton afterSignOutUrl="/goodbye">
      <button className="logout-btn">Logout</button>
    </SignOutButton>
  );
}
Props:
PropTypeDefaultDescription
childrenReactNode-Custom button element
classNamestring-CSS class for default button
afterSignOutUrlstring"/"Redirect URL after sign out

<ForgotPassword />

Complete password reset flow with automatic method detection:
import { ForgotPassword } from '@insforge/react';

function ForgotPasswordPage() {
  return (
    <ForgotPassword
      onError={(error) => console.error('Error:', error)}
    />
  );
}
Key Features:
  • Auto-detects reset method (code or link) from backend config
  • Link method: Sends email with reset link
  • Code method: Three-step flow (email → verify code → reset password)
  • 60-second countdown timer for resend
  • Built-in form validation
Props:
PropTypeDescription
onError(error: Error) => voidCallback on error

<ResetPassword />

Password reset form that reads the token from URL automatically:
import { ResetPassword } from '@insforge/react';

// Used at /reset-password?token=xxxxx
function ResetPasswordPage() {
  return (
    <ResetPassword
      onError={(error) => console.error('Error:', error)}
    />
  );
}
Key Features:
  • Automatically reads reset token from URL (?token=xxx)
  • Password confirmation validation
  • Password strength validation based on backend config
  • Success state with completion message
  • Error handling for invalid/missing tokens
Props:
PropTypeDescription
titlestringCustom title text
subtitlestringCustom subtitle text
newPasswordLabelstringLabel for new password input
newPasswordPlaceholderstringPlaceholder for new password
confirmPasswordLabelstringLabel for confirm password input
confirmPasswordPlaceholderstringPlaceholder for confirm password
submitButtonTextstringText for submit button
loadingButtonTextstringText while loading
onError(error: Error) => voidCallback on error

<VerifyEmail />

Email verification component with automatic token handling:
import { VerifyEmail } from '@insforge/react';

function VerifyEmailPage() {
  const token = new URLSearchParams(window.location.search).get('token');

  return (
    <VerifyEmail
      token={token || ''}
      onSuccess={(data) => {
        console.log('Email verified!', data);
        // Navigate to dashboard or close window
      }}
      onError={(error) => console.error('Verification failed:', error)}
    />
  );
}
Key Features:
  • Automatic verification on mount
  • Loading, success, and error states
  • Customizable status messages
Props:
PropTypeDescription
tokenstringVerification token from URL
verifyingTitlestringTitle shown while verifying
successTitlestringTitle shown on success
successMessagestringMessage shown on success
errorTitlestringTitle shown on error
onSuccess(data) => voidCallback on successful verification
onError(error: Error) => voidCallback on error

<Protect />

Protected content with conditional rendering:
import { Protect } from '@insforge/react';

function Dashboard() {
  return (
    <div>
      <h1>Dashboard</h1>
      {/* Simple protection */}
      <Protect redirectTo="/sign-in">
        <UserContent />
      </Protect>
      {/* Custom logic */}
      <Protect condition={(user) => user.subscription === 'premium'} fallback={<UpgradePrompt />}>
        <PremiumFeature />
      </Protect>
    </div>
  );
}
Props:
  • redirectTo - URL to redirect if not authorized
  • condition - Custom condition function (user) => boolean
  • fallback - React node to show if not authorized

<SignedIn> / <SignedOut>

Conditional rendering based on auth state:
import { SignedIn, SignedOut } from '@insforge/react';

function NavBar() {
  return (
    <nav>
      <SignedOut>
        <a href="/sign-in">Sign In</a>
        <a href="/sign-up">Sign Up</a>
      </SignedOut>

      <SignedIn>
        <a href="/dashboard">Dashboard</a>
        <UserButton />
      </SignedIn>
    </nav>
  );
}

Hooks

useAuth()

Access authentication methods and state. This is an alias for useInsforge().
import { useAuth } from '@insforge/react';

function LoginButton() {
  const { signIn, signUp, signOut, isSignedIn, isLoaded } = useAuth();

  const handleSignIn = async () => {
    const result = await signIn('[email protected]', 'password');
    if ('error' in result) {
      console.error('Sign in failed:', result.error);
    }
  };

  if (!isLoaded) return <div>Loading...</div>;

  return (
    <button onClick={isSignedIn ? signOut : handleSignIn}>
      {isSignedIn ? 'Sign Out' : 'Sign In'}
    </button>
  );
}
Returns:
Property/MethodTypeDescription
isLoadedbooleanWhether auth state has been initialized
isSignedInbooleanWhether user is currently signed in
signIn(email, password)PromiseSign in with email/password
signUp(email, password)PromiseRegister new user
signOut()Promise<void>Sign out current user

useInsforge()

Full access to all authentication methods and context. Use this when you need advanced features like OAuth or email verification.
import { useInsforge } from '@insforge/react';

function CustomAuthFlow() {
  const {
    // State
    user,
    isLoaded,
    isSignedIn,
    
    // Core auth
    signIn,
    signUp,
    signOut,
    
    // User management
    updateUser,
    reloadAuth,
    
    // Email verification
    resendVerificationEmail,
    verifyEmail,
    
    // Password reset
    sendResetPasswordEmail,
    resetPassword,
    exchangeResetPasswordToken,
    
    // OAuth
    loginWithOAuth,
    
    // Config
    getPublicAuthConfig,
    baseUrl,
    afterSignInUrl,
  } = useInsforge();

  // Example: OAuth login
  const handleGoogleLogin = () => {
    loginWithOAuth('google', '/dashboard');
  };

  // Example: Send password reset email
  const handleForgotPassword = async (email: string) => {
    const result = await sendResetPasswordEmail(email);
    if (result?.message) {
      console.log('Reset email sent!');
    }
  };

  return <div>...</div>;
}
Full API Reference:
Property/MethodTypeDescription
userInsforgeUser | nullCurrent user object
userIdstring | nullCurrent user ID
isLoadedbooleanAuth state initialized
isSignedInbooleanUser is signed in
signIn(email, password)PromiseSign in with credentials
signUp(email, password)PromiseRegister new user
signOut()Promise<void>Sign out user
updateUser(profile)PromiseUpdate user profile
reloadAuth()PromiseRefresh auth state from backend
resendVerificationEmail(email)PromiseResend email verification link or otp
verifyEmail(otp, email?)PromiseVerify email with OTP code
sendResetPasswordEmail(email)PromiseSend password reset email
resetPassword(token, newPassword)PromiseReset password with token
exchangeResetPasswordToken(email, code)PromiseExchange reset code for token
loginWithOAuth(provider, redirectTo)Promise<void>Start OAuth flow
getPublicAuthConfig()PromiseGet auth configuration
baseUrlstringInsForge backend URL
afterSignInUrlstringDefault redirect after sign in

useUser()

Access current user data and update profile:
import { useUser } from '@insforge/react';

function UserProfile() {
  const { user, isLoaded, updateUser } = useUser();

  if (!isLoaded) return <div>Loading...</div>;
  if (!user) return <div>Not signed in</div>;

  const handleUpdate = async () => {
    const result = await updateUser({ name: 'New Name' });
    if (result?.error) {
      console.error('Update failed:', result.error);
    }
  };

  return (
    <div>
      <p>Email: {user.email}</p>
      <p>Name: {user.profile.name}</p>
      <img src={user.profile.avatar_url} alt="Avatar" />
      <button onClick={handleUpdate}>Update Name</button>
    </div>
  );
}
Returns:
Property/MethodTypeDescription
userInsforgeUser | nullUser object with id, email, profile
user.profileobjectProfile with name, avatar_url, and custom fields
isLoadedbooleanWhether auth state is loaded
updateUser(profile)PromiseUpdate user profile data

usePublicAuthConfig()

Get your authentication configuration from InsForge backend:
import { usePublicAuthConfig } from '@insforge/react';

function CustomSignIn() {
  const { authConfig } = usePublicAuthConfig();

  return (
    <div>
      <p>Available OAuth: {authConfig?.oAuthProviders?.join(', ')}</p>
      <p>Password min length: {authConfig?.passwordMinLength}</p>
      <p>Require uppercase: {authConfig?.requireUppercase ? 'Yes' : 'No'}</p>
    </div>
  );
}
Returns:
PropertyTypeDescription
authConfigobject | nullAuth configuration from dashboard
authConfig.oAuthProviders["google", "github", "discord", "linkedin", "facebook", "instagram", "tiktok", "apple", "x", "spotify", "microsoft"]Enabled OAuth providers
authConfig.passwordMinLengthnumberMinimum password length
authConfig.requireUppercasebooleanRequire uppercase letter
authConfig.requireLowercasebooleanRequire lowercase letter
authConfig.requireNumberbooleanRequire number
authConfig.requireSpecialCharbooleanRequire special character
Performance: Only use this hook in SignIn/SignUp components. Using it elsewhere causes unnecessary API calls on every page load.

Advanced Features

InsforgeProvider Props

The provider accepts several optional props for advanced use cases:
<InsforgeProvider
  client={insforge}
  afterSignInUrl="/dashboard"
  onAuthChange={(user) => {
    if (user) {
      console.log('User signed in:', user.email);
      analytics.identify(user.id);
    } else {
      console.log('User signed out');
      analytics.reset();
    }
  }}
  onSignIn={async (authToken, user) => {
    // Sync token to cookies for SSR (Next.js)
    await fetch('/api/auth/sync', {
      method: 'POST',
      body: JSON.stringify({ token: authToken }),
    });
  }}
  onSignOut={async () => {
    // Clear server-side session
    await fetch('/api/auth/logout', { method: 'POST' });
  }}
>
  {children}
</InsforgeProvider>
Props:
PropTypeDefaultDescription
clientInsForgeClientrequiredSDK client instance
afterSignInUrlstring"/"Default redirect URL after sign in
onAuthChange(user: InsforgeUser | null) => void-Callback when auth state changes
onSignIn(authToken: string, user: InsforgeUser) => Promise<void>-Custom handler after sign-in (e.g., cookie sync)
onSignOut() => Promise<void>-Custom handler after sign-out
onRefresh(authToken: string, user: InsforgeUser) => Promise<void>-Custom handler after token refresh

Text Customization

All complete components support full text customization:
<SignIn
  title="Welcome Back!"
  subtitle="We're happy to see you again"
  emailLabel="Your Email Address"
  emailPlaceholder="[email protected]"
  passwordLabel="Your Password"
  submitButtonText="Login Now"
  loadingButtonText="Signing you in..."
  signUpText="New to our platform?"
  signUpLinkText="Create an account"
  dividerText="or continue with"
/>