@saxenapackages/auth-sdk
v1.0.9
Published
A production-grade, highly customizable React Authentication SDK
Readme
React Authentication SDK (@saxenapackages/auth-sdk)
A production-grade, highly customizable React Authentication SDK similar to Clerk, Auth0, or Firebase Auth UI.
Designed to seamlessly connect to any custom REST API microservice with zero backend changes required. Features built-in automatic silent token refresh, dynamic payload translation (requestMapping & responseMapping), lifecycle event subscriptions, modular component overrides, and dark/light UI themes.
🚀 Live Interactive Playground: https://auth-sdk-playground.vercel.app/
Quick Table of Contents
- Live Playground Demo
- Features
- Installation
- Step-by-Step Integration Guide
- Step 1: Import Styles & Setup
AuthProvider - Step 2: Choose Your UI Integration Pattern
- Step 3: Accessing Session & Protecting Routes
- Step 4: Listening to Global Lifecycle Events
- Step 5: Adapting to Any Backend (Field & Payload Mapping)
- Step 6: Custom API Callbacks & Intercept Mode (
isExternalApiCall: true) - Step 7: Custom Theming & Component Overrides
- Step 1: Import Styles & Setup
- Detailed Documentation Index
Features
- 🔐 Silent Token Management: Automatic background refresh, concurrency request queuing on 401 response, refresh locking mechanism, and secure storage management.
- 🌐 OAuth Callback Token Restoration: Auto-extracts tokens from URL parameters on Google OAuth redirects, authenticates session, and cleans up query params from address bar.
- 🔄 Universal Backend Compatibility: Custom
requestMappingandresponseMappingtransform request inputs and handle nested backend responses (dot-notation supported). - 🎨 Pre-built UI & Dark/Light Themes: Modern glassmorphism design with Light, Dark, or Custom HSL palette support out of the box.
- 🧱 3 Flexible Integration Modes: Drop-in widget (
AuthWidget), individual modular cards, or completely headless via React hooks. - ⚡ Global Event Bus: Subscribe to authentication events (
LOGIN_SUCCESS,LOGOUT,TOKEN_EXPIRED,OTP_SENT,PASSWORD_RESET). - 🧩 UI Component Overrides: Swap out buttons, inputs, cards, or loading spinners with your own component library (Tailwind, Shadcn, MUI, AntD).
- 🛡️ Built for Security & Accessibility: WAI-ARIA compliant inputs, auto-logout on invalid tokens, XSS/CSRF token defense strategies.
Installation
Install @saxenapackages/auth-sdk along with required peer dependencies using your preferred package manager:
# npm
npm install @saxenapackages/auth-sdk
# pnpm
pnpm add @saxenapackages/auth-sdk
# yarn
yarn add @saxenapackages/auth-sdkStep-by-Step Integration Guide
Step 1: Import Styles & Setup AuthProvider
At your application root (e.g., main.tsx or index.tsx), import the SDK's CSS file and wrap your application in <AuthProvider>:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider, AuthConfig } from '@saxenapackages/auth-sdk';
// ⚠️ REQUIRED: Import the SDK stylesheet
import '@saxenapackages/auth-sdk/dist/auth-sdk.css';
import App from './App';
// Define your authentication microservice configuration
const sdkConfig: AuthConfig = {
apiBaseUrl: 'https://api.yourdomain.com', // Your backend base URL
site: 'localhost',
endpoints: {
login: '/identity/signin',
signup: '/identity/signup',
verifyIdentity: '/identity/verify',
verifyOtp: '/identity/otp/validate',
resetPassword: '/identity/reset',
refreshToken: '/identity/access-token',
logout: '/logout',
getUser: '/identity',
updateUser: '/identity/update'
},
storage: 'localStorage', // 'localStorage' | 'sessionStorage' | 'memory'
tokenKey: 'accessToken',
refreshTokenKey: 'refreshToken',
theme: 'dark', // 'light' | 'dark' | custom color object
enableRefreshToken: true,
autoRefresh: true
};
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<AuthProvider config={sdkConfig}>
<App />
</AuthProvider>
</React.StrictMode>
);Step 2: Choose Your UI Integration Pattern
The SDK supports three distinct ways to implement authentication into your user interface:
Option A: Drop-in Auth Widget (Easiest)
The AuthWidget component manages the entire multi-step auth workflow internally (Login, Registration, Forgot Password, OTP Verification, Password Reset, and Profile Update):
import React from 'react';
import { AuthWidget } from '@saxenapackages/auth-sdk';
export function AuthScreen() {
return (
<div style={{ maxWidth: '440px', margin: '2rem auto' }}>
<AuthWidget
view="login" // Initial view: 'login' | 'signup' | 'forgotPassword' | 'otp' | 'resetPassword' | 'updateUser'
onSuccess={(view, data) => {
console.log(`Successfully completed action in view "${view}":`, data);
}}
onError={(view, error) => {
console.error(`Error occurred in view "${view}":`, error);
}}
/>
</div>
);
}How the Widget Routing Flow Works:
graph TD
A[Login Screen] -->|Forgot Password Click| B[ForgotPassword Screen]
A -->|Signup Click| C[Signup Screen]
C -->|API requires OTP| D[OTP Verification Screen]
B -->|API dispatches OTP| D
D -->|OTP Verified| E[Reset Password Screen]
E -->|Password Updated| AOption B: Individual Page Components
If your application uses dedicated page routes (e.g. /login, /signup, /forgot-password), render individual standalone components:
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { Login, Signup, ForgotPassword, OTP } from '@saxenapackages/auth-sdk';
// 1. Dedicated Login Page
export function LoginPage() {
const navigate = useNavigate();
return (
<Login
onSuccess={() => navigate('/dashboard')}
onSignupClick={() => navigate('/signup')}
onForgotPasswordClick={() => navigate('/forgot-password')}
/>
);
}
// 2. Dedicated Signup Page
export function SignupPage() {
const navigate = useNavigate();
return (
<Signup
onSuccess={(data) => {
// If your flow requires OTP verification after signup:
navigate('/verify-otp', { state: { email: data.email } });
}}
onLoginClick={() => navigate('/login')}
/>
);
}Available standalone components:
<Login /><Signup /><ForgotPassword /><OTP /><ResetPassword /><GoogleLogin /><UpdateUser /><Alert />
Option C: Headless Integration with React Hooks
If you want to build a completely custom UI using your own forms and buttons, use the built-in React hooks:
import React, { useState } from 'react';
import { useLogin, useAuth } from '@saxenapackages/auth-sdk';
export function CustomLoginForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const { execute, loading, error } = useLogin();
const { isAuthenticated, user } = useAuth();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await execute({ email, password });
alert('Login successful!');
} catch (err) {
console.error('Failed to log in:', err);
}
};
if (isAuthenticated) {
return <div>Welcome back, {user?.name || user?.email}!</div>;
}
return (
<form onSubmit={handleSubmit}>
<h2>Sign In</h2>
{error && <div className="error-message">{error}</div>}
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter your password"
required
/>
<button type="submit" disabled={loading}>
{loading ? 'Signing in...' : 'Sign In'}
</button>
</form>
);
}Full Hooks Catalog:
| Hook | Returns | Purpose |
| :--- | :--- | :--- |
| useAuth() | { user, token, isAuthenticated, loading, logout, refresh } | Access global session state & auth functions. |
| useLogin() | { execute, loading, error, success } | Submit user login credentials. |
| useSignup() | { execute, loading, error, success } | Register a new user profile. |
| useVerifyIdentity() | { execute, loading, error, success } | Send verification/OTP code to user's email. |
| useOtp() | { execute, resend, loading, error, success } | Validate OTP digit code or trigger code resend. |
| useResetPassword() | { execute, loading, error, success } | Submit new password after OTP verification. |
| useUpdateUser() | { execute, loading, error, success } | Update profile info (Name, Username, Email, etc.). |
Step 3: Accessing Session & Protecting Routes
Use the useAuth() hook anywhere in your component tree to check authentication status or create protected route guards:
Protecting App Routes Example:
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '@saxenapackages/auth-sdk';
export function ProtectedRoute() {
const { isAuthenticated, loading } = useAuth();
if (loading) {
return <div>Loading authentication session...</div>;
}
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return <Outlet />;
}User Profile / Header Component Example:
import React from 'react';
import { useAuth } from '@saxenapackages/auth-sdk';
export function Header() {
const { user, isAuthenticated, logout } = useAuth();
if (!isAuthenticated) {
return <a href="/login">Sign In</a>;
}
return (
<header style={{ display: 'flex', justifyContent: 'space-between', padding: '1rem' }}>
<span>Welcome, {user?.name || user?.email}</span>
<button onClick={() => logout()}>Log Out</button>
</header>
);
}Step 4: Listening to Global Lifecycle Events
The SDK includes a global Pub/Sub event bus (eventService). Listen to authentication events from anywhere in your app to trigger routing, toast notifications, or analytics:
import { useEffect } from 'react';
import { eventService } from '@saxenapackages/auth-sdk';
import { useNavigate } from 'react-router-dom';
export function EventSubscriber() {
const navigate = useNavigate();
useEffect(() => {
const handleLoginSuccess = (data: any) => {
console.log('Login Event:', data);
};
const handleTokenExpired = () => {
alert('Your session has expired. Please log in again.');
navigate('/login');
};
const handleOtpSent = () => {
console.log('OTP dispatched to user email.');
};
// Subscribe to events
eventService.on('LOGIN_SUCCESS', handleLoginSuccess);
eventService.on('TOKEN_EXPIRED', handleTokenExpired);
eventService.on('OTP_SENT', handleOtpSent);
// Clean up subscriptions
return () => {
eventService.off('LOGIN_SUCCESS', handleLoginSuccess);
eventService.off('TOKEN_EXPIRED', handleTokenExpired);
eventService.off('OTP_SENT', handleOtpSent);
};
}, [navigate]);
return null;
}Supported Lifecycle Events:
LOGIN_SUCCESS: Triggered on successful credentials validation.LOGIN_FAILED: Triggered when login fails.LOGOUT: Triggered when session is terminated.OTP_SENT: Triggered when an OTP code is requested/dispatched.OTP_VERIFIED: Triggered when an OTP code passes validation.PASSWORD_RESET: Triggered when a new password is set.TOKEN_EXPIRED: Triggered when silent renew fails or session expires.
Step 5: Adapting to Any Backend (Field & Payload Mapping)
No need to rewrite your backend API! Map your custom request fields and backend response JSON structures inside your SDK configuration:
1. requestMapping: Translate Form Fields to Backend Parameters
const config: AuthConfig = {
apiBaseUrl: 'https://api.yourdomain.com',
requestMapping: {
login: {
email: 'username', // Maps SDK 'email' field -> backend payload 'username'
password: 'pass' // Maps SDK 'password' field -> backend payload 'pass'
},
signup: {
name: 'full_name',
email: 'contact_email',
password: 'user_password'
}
}
};2. responseMapping: Extract Access Tokens & User Objects from Nested JSON
Supports dot-notation syntax (data.result.token) for deeply nested response payloads:
const config: AuthConfig = {
apiBaseUrl: 'https://api.yourdomain.com',
responseMapping: {
token: 'data.tokens.jwt', // Target JWT token in response JSON
refreshToken: 'data.tokens.refresh', // Target refresh token
user: 'data.userProfile' // Target user profile object
}
};Step 6: Custom API Callbacks & Intercept Mode (isExternalApiCall: true)
If your application uses GraphQL, Firebase, Supabase, tRPC, or custom client libraries (instead of standard Axios REST HTTP calls), or if you want to mock authentication responses for local testing, set isExternalApiCall: true and pass custom callback functions:
import { AuthConfig } from '@saxenapackages/auth-sdk';
const sdkConfig: AuthConfig = {
// 1. Enable Bypass / Intercept Mode
isExternalApiCall: true,
// 2. Provide custom promise callbacks for each auth action
onLogin: async (payload) => {
// Custom GraphQL / Firebase / API request logic:
const data = await myCustomAuthClient.login(payload.email, payload.password);
return {
token: data.jwtToken,
refreshToken: data.refreshToken,
user: data.userProfile
};
},
onSignup: async (payload) => {
const data = await myCustomAuthClient.register(payload);
return { id: data.userId, email: data.email };
},
onGoogleLogin: async (params) => {
// Custom OAuth endpoint or popup handler
// Receives optional params (e.g. { redirectUrl: '...' }) passed from <GoogleLogin redirectUrl="..." />
const data = await myCustomAuthClient.getGoogleOAuthUrl(params);
// Return object containing redirectUrl/url (or session tokens if authenticating directly):
return { redirectUrl: data.url };
},
onVerifyOtp: async (payload, urlParams) => {
const res = await myCustomAuthClient.verifyOtp(payload.otp);
return { success: true, token: res.jwt };
},
onResetPassword: async (payload, urlParams) => {
await myCustomAuthClient.resetPassword(payload.password);
return { success: true };
},
onUpdateUser: async (payload, site, id) => {
const updatedUser = await myCustomAuthClient.updateProfile(id, payload);
return updatedUser;
},
onLogout: async () => {
await myCustomAuthClient.signOut();
}
};Available Callback Overrides:
onLogin(payload)onSignup(payload)onVerifyIdentity(payload, urlParams)onVerifyOtp(payload, urlParams)onResetPassword(payload, urlParams)onUpdateUser(payload, site, id)onDeleteUser(site, id)onGoogleLogin(params)onLogout()onRefresh(refreshToken)onGetUser(site, id)
Step 7: Custom Theming & Component Overrides
Dynamic Theming (Light, Dark, or Custom HSL)
Configure built-in themes or supply custom HSL color values:
const config: AuthConfig = {
apiBaseUrl: 'https://api.yourdomain.com',
theme: {
colors: {
primary: '#6366f1',
primaryHover: '#4f46e5',
secondary: '#ec4899',
background: '#0f172a',
surface: '#1e293b',
text: '#f8fafc',
textMuted: '#94a3b8',
timer: '#f59e0b', // Custom Resend OTP timer color
borderOuter: 'transparent', // Outer card border color
borderOuterHover: '#6366f1', // Outer card border color on hover
borderInner: '#334155', // Form input field inner border
borderInnerHover: '#6366f1', // Form input field focus border
shadow: '#000000', // Ambient card shadow color
error: '#f87171',
success: '#4ade80'
},
borderWidth: '1px', // Outer border width (e.g. '1px', '2px')
borderRadiusCard: '16px', // Outer card border radius
},
customization: {
colors: {
timer: '#f59e0b'
},
alert: {
autoDismiss: true, // Auto-dismiss alert banners (default: true)
duration: 3 // Duration in seconds (default: 3 seconds)
}
}
};Top Card Header Icon Configuration
Add custom logos, brand icons, or SVG images at the top of every auth card component globally via config.customization.headerIcon or per component via config.customization.icons:
const config: AuthSdkConfig = {
apiBaseUrl: 'https://api.yourdomain.com',
customization: {
// Global header icon URL or SVG string rendered at top of every component card
headerIcon: 'https://yourdomain.com/logo.png',
// Optional global header icon size (e.g. '48px', '64px', '32px', 64)
headerIconSize: '48px',
// Or component-specific icons
icons: {
login: 'https://yourdomain.com/icons/login.png',
signup: 'https://yourdomain.com/icons/signup.png',
otp: '<svg ...></svg>', // Supports SVG string directly
}
}
};Component Overrides
Replace internal UI elements (Buttons, Inputs, Cards, Loaders, HeaderIcons) with custom design system components (e.g., Shadcn, Tailwind, MUI):
import { Login, HeaderIcon } from '@saxenapackages/auth-sdk';
import { Button, TextField, Paper, CircularProgress } from '@mui/material';
export function CustomStyledLogin() {
return (
<Login
headerIcon="https://yourdomain.com/logo.png"
components={{
Card: (props) => <Paper {...props} elevation={4} style={{ padding: '2rem' }} />,
Button: (props) => <Button {...props} variant="contained" fullWidth color="primary" />,
Input: (props) => <TextField {...props} fullWidth variant="outlined" margin="normal" />,
HeaderIcon: () => <img src="/logo.svg" alt="App Logo" style={{ width: 48, height: 48 }} />,
Loader: CircularProgress
}}
/>
);
}Detailed Documentation Index
For in-depth explanations, configuration options, and migration walkthroughs, explore the complete guide files in the docs/ folder:
- ⚙️ Configuration Guide (docs/Configuration.md) — In-depth parameter reference, custom endpoints, storage managers, and validation schemas.
- 🪝 Hooks Reference (docs/Hooks.md) — Exhaustive specification for
useAuth,useLogin,useSignup,useOtp, etc. - 📡 API Client, Events & Errors (docs/API.md) — Axios interceptors, silent token renewal lock queueing, and error code normalization.
- 🎨 Theming & Customization (docs/Theme.md) — Styling variables, sub-component replacement, dark mode, and custom translations.
- 🚀 Migration Guide (docs/Migration.md) — Guide on replacing legacy custom auth flows with the SDK.
