InsForge provides three levels of flexibility for implementing authentication in your app:
Key Difference from Hosted Auth
| Aspect | Hosted Auth | Custom Components |
|---|
| Sign-in route | Redirects to https://your-app.region.insforge.app/auth/sign-in | Renders your <SignIn /> component |
| Where auth happens | On hosted page | In your app |
| Token management | Returns to your app with token | SDK 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:
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,
});
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:
| Prop | Type | Description |
|---|
title | string | Custom title text |
subtitle | string | Custom subtitle text |
emailLabel | string | Label for email input |
emailPlaceholder | string | Placeholder for email input |
passwordLabel | string | Label for password input |
passwordPlaceholder | string | Placeholder for password input |
forgotPasswordText | string | Text for forgot password link |
forgotPasswordUrl | string | URL for forgot password page |
submitButtonText | string | Text for submit button |
loadingButtonText | string | Text while loading |
signUpText | string | Text before sign up link |
signUpLinkText | string | Text for sign up link |
signUpUrl | string | URL for sign up page |
dividerText | string | Text in OAuth divider |
onError | (error: Error) => void | Callback 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:
| Prop | Type | Description |
|---|
title | string | Custom title text |
subtitle | string | Custom subtitle text |
emailLabel | string | Label for email input |
emailPlaceholder | string | Placeholder for email input |
passwordLabel | string | Label for password input |
passwordPlaceholder | string | Placeholder for password input |
submitButtonText | string | Text for submit button |
loadingButtonText | string | Text while loading |
signInText | string | Text before sign in link |
signInLinkText | string | Text for sign in link |
signInUrl | string | URL for sign in page |
dividerText | string | Text in OAuth divider |
onError | (error: Error) => void | Callback on error |
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:
| Prop | Type | Default | Description |
|---|
mode | "detailed" | "simple" | "simple" | detailed: avatar + name + email, simple: avatar only |
afterSignOutUrl | string | "/" | Redirect URL after sign out |
showProfile | boolean | true | Show 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:
| Prop | Type | Description |
|---|
onClose | () => void | Called when modal is closed |
onError | (error: string) => void | Called when an error occurs |
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:
| Prop | Type | Description |
|---|
children | ReactNode | Custom button element (wraps with click handler) |
className | string | CSS class for default button |
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:
| Prop | Type | Default | Description |
|---|
children | ReactNode | - | Custom button element |
className | string | - | CSS class for default button |
afterSignOutUrl | string | "/" | 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:
| Prop | Type | Description |
|---|
onError | (error: Error) => void | Callback 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:
| Prop | Type | Description |
|---|
title | string | Custom title text |
subtitle | string | Custom subtitle text |
newPasswordLabel | string | Label for new password input |
newPasswordPlaceholder | string | Placeholder for new password |
confirmPasswordLabel | string | Label for confirm password input |
confirmPasswordPlaceholder | string | Placeholder for confirm password |
submitButtonText | string | Text for submit button |
loadingButtonText | string | Text while loading |
onError | (error: Error) => void | Callback 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:
| Prop | Type | Description |
|---|
token | string | Verification token from URL |
verifyingTitle | string | Title shown while verifying |
successTitle | string | Title shown on success |
successMessage | string | Message shown on success |
errorTitle | string | Title shown on error |
onSuccess | (data) => void | Callback on successful verification |
onError | (error: Error) => void | Callback 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/Method | Type | Description |
|---|
isLoaded | boolean | Whether auth state has been initialized |
isSignedIn | boolean | Whether user is currently signed in |
signIn(email, password) | Promise | Sign in with email/password |
signUp(email, password) | Promise | Register 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/Method | Type | Description |
|---|
user | InsforgeUser | null | Current user object |
userId | string | null | Current user ID |
isLoaded | boolean | Auth state initialized |
isSignedIn | boolean | User is signed in |
signIn(email, password) | Promise | Sign in with credentials |
signUp(email, password) | Promise | Register new user |
signOut() | Promise<void> | Sign out user |
updateUser(profile) | Promise | Update user profile |
reloadAuth() | Promise | Refresh auth state from backend |
resendVerificationEmail(email) | Promise | Resend email verification link or otp |
verifyEmail(otp, email?) | Promise | Verify email with OTP code |
sendResetPasswordEmail(email) | Promise | Send password reset email |
resetPassword(token, newPassword) | Promise | Reset password with token |
exchangeResetPasswordToken(email, code) | Promise | Exchange reset code for token |
loginWithOAuth(provider, redirectTo) | Promise<void> | Start OAuth flow |
getPublicAuthConfig() | Promise | Get auth configuration |
baseUrl | string | InsForge backend URL |
afterSignInUrl | string | Default 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/Method | Type | Description |
|---|
user | InsforgeUser | null | User object with id, email, profile |
user.profile | object | Profile with name, avatar_url, and custom fields |
isLoaded | boolean | Whether auth state is loaded |
updateUser(profile) | Promise | Update 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:
| Property | Type | Description |
|---|
authConfig | object | null | Auth configuration from dashboard |
authConfig.oAuthProviders | ["google", "github", "discord", "linkedin", "facebook", "instagram", "tiktok", "apple", "x", "spotify", "microsoft"] | Enabled OAuth providers |
authConfig.passwordMinLength | number | Minimum password length |
authConfig.requireUppercase | boolean | Require uppercase letter |
authConfig.requireLowercase | boolean | Require lowercase letter |
authConfig.requireNumber | boolean | Require number |
authConfig.requireSpecialChar | boolean | Require 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:
| Prop | Type | Default | Description |
|---|
client | InsForgeClient | required | SDK client instance |
afterSignInUrl | string | "/" | 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"
/>