Framework-agnostic React authentication UI components for Insforge - reusable across all frameworks
RouteGuard for vanilla React apps
bash
npm install @insforge/react
or
yarn add @insforge/react
or
pnpm add @insforge/react
`
#### Environment Variables
`bash
.env
VITE_INSFORGE_BASE_URL=https://your-project.insforge.app/
`
$3
Wrap your app with InsforgeProvider:
`tsx
// src/main.tsx (Vite) or src/index.tsx (CRA)
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { InsforgeProvider } from '@insforge/react';
import App from './App';
createRoot(document.getElementById('root')!).render(
);
`
$3
Now you can use authentication components and hooks anywhere in your app:
`tsx
// src/App.tsx
import { SignInButton, SignUpButton, SignedIn, SignedOut, UserButton } from '@insforge/react';
export default function App() {
return (
Welcome to your dashboard!
);
}
`
That's it! 🎉 Your app is now protected with authentication.
---
Usage Patterns
$3
Use complete auth flows with built-in UI and logic:
`tsx
import { SignIn, SignUp, ForgotPassword, ResetPassword } from '@insforge/react';
// In your app
// Complete sign-in flow
// Complete sign-up flow with email verification
// Password reset request + verification
// Reset password with token (from URL params)
`
$3
Use UI components and add your own logic:
`tsx
import { SignInForm, useAuth } from '@insforge/react';
import { useState } from 'react';
function CustomSignIn() {
const { signIn } = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
const result = await signIn(email, password);
if ('error' in result) {
setError(result.error);
}
setLoading(false);
};
return (
email={email}
password={password}
onEmailChange={setEmail}
onPasswordChange={setPassword}
onSubmit={handleSubmit}
error={error}
loading={loading}
/>
);
}
`
$3
Build completely custom UI using authentication hooks:
`tsx
import { useAuth } from '@insforge/react';
function CustomAuthForm() {
const { signIn, signUp, isLoaded } = useAuth();
const handleLogin = async (email: string, password: string) => {
const result = await signIn(email, password);
if ('error' in result) {
console.error(result.error);
} else {
console.log('Signed in!');
}
};
return ;
}
`
---
Core Features
$3
Pre-built with Business Logic:
- - Complete sign-in with email/password & OAuth
- - Registration with password validation & email verification
- - Request password reset with email validation
- - Reset password with token validation
- - Verify email with automatic token handling
- - User dropdown with sign-out
- - NEW: App-level route protection for vanilla React
- - Component-level protection wrapper
- / - Conditional rendering
Form Components (Pure UI):
- - Sign-in UI without logic
- - Sign-up UI without logic
- - Password reset request UI
- - Password reset with token UI
- - Email verification status UI
Atomic Components (14 total):
- , , , , , etc.
$3
`tsx
// Authentication state and methods
const {
signIn,
signUp,
signOut,
isSignedIn,
isLoaded,
baseUrl, // From provider
afterSignInUrl, // From provider
} = useAuth();
// Or use useInsforge (same as useAuth)
const context = useInsforge();
// User information
const { user, updateUser, isLoaded } = useUser();
// Public auth configuration (OAuth providers, password requirements, etc.)
const { oauthProviders, authConfig, isLoaded } = usePublicAuthConfig();
`
---
Customization
$3
All components support full text customization:
`tsx
title="Welcome Back!"
subtitle="We're happy to see you again"
emailLabel="Your Email Address"
emailPlaceholder="you@company.com"
passwordLabel="Your Password"
submitButtonText="Login Now"
loadingButtonText="Signing you in..."
signUpText="New to our platform?"
signUpLinkText="Create an account"
dividerText="or continue with"
/>
title="Reset Your Password"
subtitle="Enter your email to receive a reset code"
emailLabel="Email Address"
submitButtonText="Send Reset Code"
backToSignInText="Remember your password?"
successTitle="Check Your Email"
successMessage="We've sent a reset code to your inbox"
/>
`
---
Advanced Usage
$3
Control what users see based on auth state:
`tsx
import { SignedIn, SignedOut, Protect } from '@insforge/react';
function App() {
return (
<>
{/ Or use Protect for specific sections /}
>
);
}
`
$3
`tsx
import {
AuthContainer,
AuthHeader,
AuthFormField,
AuthPasswordField,
AuthSubmitButton,
AuthErrorBanner,
AuthDivider,
AuthOAuthProviders,
AuthLink,
} from '@insforge/react';
function CompletelyCustomAuth() {
return (
providers={['google', 'github', 'discord']}
onClick={handleOAuth}
loading={oauthLoading}
/>
);
}
`
$3
Protect specific content or sections:
`tsx
import { Protect } from '@insforge/react';
function Dashboard() {
return (
Dashboard
{/ Simple protection - shows nothing if not signed in /}
{/ With redirect /}
{/ Custom condition - e.g., role-based /}
user.email.endsWith('@admin.com')} redirectTo="/unauthorized">
);
}
`
> Note: is for component-level conditional rendering. For app-level route protection, use
---
Route Protection (Detailed)
$3
RouteGuard provides app-level authentication protection without requiring any routing library.
#### Option 1: External Built-in Auth (Simplest)
Redirects to your deployed Insforge Auth pages:
`tsx
import { InsforgeProvider, RouteGuard } from '@insforge/react';
createRoot(document.getElementById('root')!).render(
builtInAuth
publicRoutes={['/', '/about', '/pricing']}
loadingFallback={Loading...}
>
Behavior:
- User visits /sign-in → Redirects to baseUrl/auth/sign-in
- User visits /sign-up → Redirects to baseUrl/auth/sign-up
- User visits /dashboard (protected) → Redirects to baseUrl/auth/sign-in
- User visits / (public) → ✅ Renders normally
#### Option 2: Custom Auth Pages
Use @insforge/react components in your own app:
`tsx
import { InsforgeProvider, RouteGuard, SignIn, SignUp } from '@insforge/react';
// Simple hash-based routing
function App() {
const path = window.location.hash.slice(1) || '/';
return (
<>
{path === '/login' && }
{path === '/register' && }
{path === '/dashboard' && }
{path === '/' && }
>
);
}
createRoot(document.getElementById('root')!).render(
builtInAuth={false}
publicRoutes={['/login', '/register', '/forgot-password', '/']}
paths={{ signIn: '/login', signUp: '/register' }}
loadingFallback={Loading...}
>
);
`
Behavior:
- User visits /login → ✅ Renders (in publicRoutes)
- User visits /dashboard (protected) → Redirects to /login?redirect=/dashboard
- After login → Redirects to /dashboard
#### RouteGuard Props Reference
| Prop | Type | Required | Default | Description |
| ---------------------- | ----------- | -------- | ----------------------------- | ---------------------------------------------------------- |
| builtInAuth | boolean | No | true | Use external auth pages (true) or custom pages (false) |
| publicRoutes | string[] | No | [] | Routes accessible without authentication |
| paths | object | No | { signIn: '/sign-in', ... } | Custom auth page paths (when builtInAuth=false) |
| paths.signIn | string | No | '/sign-in' | Custom sign-in page path |
| paths.signUp | string | No | '/sign-up' | Custom sign-up page path |
| paths.forgotPassword | string | No | '/forgot-password' | Custom forgot password page path |
| loadingFallback | ReactNode | Yes | - | Loading UI displayed while checking authentication |
Public Routes with Wildcards:
`tsx
publicRoutes={[
'/', // Home page
'/about', // About page
'/blog/*', // All blog routes
'/docs/*', // All documentation routes
]}
>
`
> Note: When builtInAuth=true, auth paths (/sign-in, /sign-up, /forgot-password) are automatically redirected. Don't include them in publicRoutes.
$3
For React Router apps, use the dedicated adapter:
`bash
npm install @insforge/react-router
`
`tsx
import { InsforgeProvider } from '@insforge/react-router';
import { getInsforgeRoutes } from '@insforge/react-router/router';
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
const router = createBrowserRouter([
{ path: '/', element: },
{ path: '/dashboard', element: },
...getInsforgeRoutes({
baseUrl: import.meta.env.VITE_INSFORGE_BASE_URL,
builtInAuth: true,
}),
]);
function App() {
return (
);
}
`
Features:
- Pre-configured routes for authentication flows
- React Router's Link and useSearchParams integration
- Optimized navigation with client-side routing
Docs: @insforge/react-router
$3
For Next.js App Router with SSR:
`bash
npm install @insforge/nextjs
`
`tsx
// app/layout.tsx
import { InsforgeProvider } from '@insforge/nextjs';
export default function RootLayout({ children }) {
return (
{children}
);
}
`
Features:
- Server-side rendering (SSR) support
- Middleware-based route protection
- Next.js Link and useSearchParams integration
- Cookie-based session management
- Automatic token refresh
Docs: @insforge/nextjs
---
OAuth Providers
Built-in support for 10+ OAuth providers:
- Google
- GitHub
- Discord
- Apple
- Microsoft
- Facebook
- LinkedIn
- Instagram
- TikTok
- Spotify
- X (Twitter)
Providers are auto-detected from your backend configuration.
---
Available Atomic Components
Low-level building blocks for complete customization:
- - Insforge branding footer
- - Main container wrapper
- - Title and subtitle display
- - Error message display
- - Standard input field
- - Password input with features
- - Password checklist
- - Submit button with states
- - Call-to-action link
- - Visual separator
- - Single OAuth provider button
- - Smart OAuth grid
- - 6-digit OTP input
- - Email verification step with countdown and resend
---
API Reference
$3
The root provider component that manages authentication state.
Props:
| Prop | Type | Required | Default | Description |
| ---------------- | -------------------------------------- | -------- | ------- | --------------------------------------------------- |
| baseUrl | string | Yes | - | Your Insforge backend URL |
| afterSignInUrl | string | No | '/' | Redirect URL after successful sign-in |
| onAuthChange | (user: InsforgeUser \| null) => void | No | - | Callback when auth state changes |
| onSignIn | (authToken: string) => Promise | No | - | Custom handler after sign-in (e.g., cookie sync) |
| onSignOut | () => Promise | No | - | Custom handler after sign-out (e.g., clear cookies) |
Example:
`tsx
baseUrl={import.meta.env.VITE_INSFORGE_BASE_URL}
afterSignInUrl="/dashboard"
onAuthChange={(user) => {
console.log('Auth changed:', user);
}}
>
{children}
`
$3
App-level route protection for vanilla React apps (no router library needed).
See Route Protection (Detailed) for full documentation.
Quick Props:
- builtInAuth (default: true) - Use external auth or custom pages
- publicRoutes - Array of paths accessible without auth
- paths - Custom auth page paths (when builtInAuth=false)
- loadingFallback (required) - Loading UI
$3
Primary hook for authentication. Both are aliases for the same hook.
Returns:
`tsx
{
// Auth state
user: InsforgeUser | null;
isLoaded: boolean;
isSignedIn: boolean;
// Auth methods
signIn: (email: string, password: string) => Promise<...>;
signUp: (email: string, password: string) => Promise<...>;
signOut: () => Promise;
updateUser: (data: Partial) => Promise<...>;
reloadAuth: () => Promise<...>;
// Email verification
resendVerificationEmail: (email: string) => Promise<...>;
verifyEmail: (otp: string, email?: string) => Promise<...>;
// Password reset
sendResetPasswordEmail: (email: string) => Promise<...>;
resetPassword: (token: string, newPassword: string) => Promise<...>;
exchangeResetPasswordToken: (email: string, code: string) => Promise<...>;
// OAuth
loginWithOAuth: (provider: OAuthProvider, redirectTo: string) => Promise;
// Config (from provider)
baseUrl: string;
afterSignInUrl: string;
// Public config
getPublicAuthConfig: () => Promise<...>;
}
`
$3
Simplified hook for user data only.
Returns:
`tsx
{
user: InsforgeUser | null;
isLoaded: boolean;
}
`
$3
Hook for fetching public auth configuration (OAuth providers, password requirements, etc.).
Returns:
`tsx
{
oauthProviders: OAuthProviderConfig[];
authConfig: AuthConfig;
isLoaded: boolean;
}
``