@zhmdff/auth-react
v3.5.0
Published
Plug and play authentication library for React/Next.js
Downloads
414
Readme
⚛️ @zhmdff/auth-react — Master Documentation
Version: 3.5.0 | Target Runtime: React 18+ / Next.js 13+ | License: MIT
The official React/Next.js client library for the Zhmdff.Auth ecosystem. Provides seamless state management, automatic token rotation, and ready-to-use UI components.
🏗 Architecture & Data Flow
Component Map
| Category | Item | Responsibility |
|:---|:---|:---|
| Context | AuthProvider | Central state for AccessToken, User, and IsLoading. |
| Hooks | useAuth | Primary hook for authentication, MFA, and authenticated fetching. |
| Hooks | useAdmin | Specialized hook for administrative operations and audit logs. |
| UI | AuthGuard | HOC/Component for protecting routes based on roles/permissions. |
| Social | GoogleLoginButton | Pre-styled interactive buttons for social providers. |
Auth Cycle
- Init:
AuthProviderchecks for an existing session via/auth/refresh. - State: User and Token are stored in memory; Refresh Token is stored in HttpOnly cookies (recommended).
- Fetch: The
fetchmethod fromuseAuthautomatically injects theAuthorizationheader and handles401errors by attempting a transparent token refresh. - Sync: User state is automatically updated across the app whenever a token is refreshed or profile updated.
🌐 Global Rules & Conventions
| Category | Rule | Implementation |
|:---|:---|:---|
| Data Format | PascalCase | Matches .NET DTOs for 1:1 mapping (e.g., User.FullName). |
| SSR Safety | Client-Only | All hooks and providers marked with "use client". |
| Token Storage | Memory + Cookies | JWT in memory for security; Refresh Token in Cookies to prevent XSS. |
| Naming | Standard Hooks | Follows use[Feature] naming convention. |
| Error Handling | Throws Exceptions | Utility functions throw on non-2xx; hooks return { Success: false }. |
⚠️ Common Pitfalls (v3.4.1 Update)
- PascalCase: Context properties are
User,IsLoading, andAccessToken. CamelCase will result inundefined. - Imports: Use
import typefor interfaces (e.g.,LoginRequest) to avoid Vite/ESM runtime errors. - Login Payload: The API expects
Identifier(Email/Username) andPassword(PascalCase).
⚙️ Configuration Reference
The AuthProvider accepts an AuthConfig object:
| Prop | Type | Default | Description |
|:---|:---|:---|:---|
| authUrl | string | Required | Base URL for authentication endpoints (e.g., .../auth). |
| apiUrl | string | Optional | Base URL for your application API. |
| loginPath | string | "/login" | Redirect path for unauthorized access. |
| onLogout | function | Optional | Callback triggered after logout. |
| endpoints | object | Optional | Override default paths for login, register, etc. |
📡 Complete Hook Registry
useAuth<TUser>()
| Method | Summary |
|:---|:---|
| login(request) | Standard login. Returns RequiresTwoFactor if MFA enabled. |
| register(request) | Registers a new user. |
| logout() | Revokes session and clears local state. |
| checkAuth() | Manually trigger a session verification/refresh. |
| fetch<T>(url, opt) | Authenticated fetch with auto-refresh and interceptors. |
| setupMfa() | Initiates TOTP setup (returns QR code URI). |
| verifyMfa(request) | Verifies a 2FA code to complete login/setup. |
| updateProfile(request)| Updates current user's metadata. |
| loginWith[Provider]() | Redirects to Social OAuth flow. |
useAdmin()
| Method | Summary |
|:---|:---|
| getUsers(page, size) | List users with search and pagination. |
| setUserStatus(id, active)| Activate or deactivate a user account. |
| updateUserRoles(id, rId) | Assign or remove roles from a user. |
| getAuditLogs(filters) | Retrieve advanced audit trail records. |
| createRole/Permission | Administrative schema management. |
🧩 Component Registry
AuthGuard
Protects children based on authentication status or specific authorization rules.
<AuthGuard roles={["Admin"]} permission="CanDeleteUsers">
<DeleteUserButton />
</AuthGuard>Social Buttons
Ready-to-use buttons that handle the redirect logic.
GoogleLoginButtonGitHubLoginButtonFacebookLoginButtonAppleLoginButton
🚀 Quick Start
import { AuthProvider } from "@zhmdff/auth-react";
export function App() {
return (
<AuthProvider authUrl="https://api.myapp.com/auth">
<MyRoutes />
</AuthProvider>
);
}