@zhmdff/auth-react
v1.2.0
Published
Plug and play authentication library for React/Next.js
Readme
@zhmdff/auth-react
Plug-and-play authentication provider for React and Next.js applications, designed to work seamlessly with the Zhmdff Auth .NET backend.
Features
- 🔐 Pre-built Auth Context: Manages access tokens, user state, and loading status.
- 🔄 Auto-Refresh: Automatically refreshes access tokens on 401 Unauthorized responses.
- 📡 Smart Fetch Wrapper: Includes a
fetchutility that automatically injects the Bearer token. - 🎣 Simple Hook:
useAuth()hook for easy access to user data and actions. - 🐍 Google OAuth:
GoogleLoginButtoncomponent andloginWithGoogle()for social login. - ⚖️ React & Next.js Compatible: Works in any React 18+ environment.
Installation
npm install @zhmdff/auth-react
# or
pnpm install @zhmdff/auth-react
# or
yarn add @zhmdff/auth-reactQuick Start
1. Wrap your application with AuthProvider
Next.js (App Router) - app/layout.tsx
import { AuthProvider } from "@zhmdff/auth-react";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<AuthProvider
authUrl={process.env.NEXT_PUBLIC_AUTH_URL}
apiUrl={process.env.NEXT_PUBLIC_API_URL}
loginPath="/login"
>
{children}
</AuthProvider>
</body>
</html>
);
}React (Vite/CRA) - src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { AuthProvider } from "@zhmdff/auth-react";
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<AuthProvider
authUrl={import.meta.env.VITE_AUTH_URL}
apiUrl={import.meta.env.VITE_API_URL}
loginPath="/login"
>
<App />
</AuthProvider>
</React.StrictMode>,
);2. Use authentication in your components
import { useAuth } from "@zhmdff/auth-react";
export default function UserProfile() {
const { user, logout, isLoading } = useAuth();
if (isLoading) return <div>Loading...</div>;
if (!user) {
return <div>Please log in to view this page.</div>;
}
return (
<div>
<h1>Welcome, {user.fullName || user.username}!</h1>
<p>Role: {user.role}</p>
<button onClick={logout}>Sign Out</button>
</div>
);
}
### 3. Protect routes with `AuthGuard`
```tsx
import { AuthGuard } from "@zhmdff/auth-react";
export default function DashboardLayout({ children }) {
return (
<AuthGuard
loadingComponent={<Spinner />}
// Required roles (optional)
allowedRoles={["Admin", "SuperAdmin"]}
// Redirects to loginPath if not authenticated
>
{children}
</AuthGuard>
);
}
## API Reference
### `AuthProvider` Props
| Prop | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| `authUrl` | `string` | Yes | The base URL for authentication endpoints. Recommended to use environment variables. |
| `apiUrl` | `string` | No | The base URL for your API. Recommended to use environment variables. |
| `loginPath` | `string` | No | Path to redirect unauthenticated users to (default: `/login`). |
| `children` | `ReactNode` | Yes | The components to be wrapped. |
### `useAuth()` Hook
Returns an object with the following properties:
- `user`: `User | null` - The current authenticated user.
- `accessToken`: `string | null` - The current JWT access token.
- `isLoading`: `boolean` - True while the initial auth check is running.
- `checkAuth`: `() => Promise<boolean>` - Manually triggers an auth check (refresh token).
- `logout`: `() => Promise<void>` - Logs the user out and clears state.
- `fetch`: `(endpoint: string, options?: any) => Promise<any>` - Authenticated fetch wrapper.
- `loginWithGoogle`: `(returnUrl?: string) => void` - Redirects to the Google OAuth flow.
### `User` Object
```typescript
export interface User {
id: string; // GUID
email?: string;
username?: string;
fullName?: string;
role: string;
roles: string[];
isActive: boolean;
emailConfirmed?: boolean;
twoFactorEnabled?: boolean;
// ...other security flags
}Google OAuth Quick Start
Requires Zhmdff.Auth v2.0.9+ on the backend with Google credentials configured.
Drop-in button
"use client";
import { GoogleLoginButton } from "@zhmdff/auth-react";
export function LoginPage() {
return (
<GoogleLoginButton
returnUrl={typeof window !== "undefined" ? window.location.origin : undefined}
/>
);
}Manual trigger
const { loginWithGoogle } = useAuth();
<button onClick={() => loginWithGoogle(window.location.origin)}>Sign in with Google</button>After Google login, the user is redirected back to your returnUrl. The AuthProvider automatically detects the session on the next load via the HttpOnly refresh cookie.
See
USAGE.mdsection 11 for the complete setup, including backend requirements and Google Cloud Console configuration.
API Reference
The fetch function from useAuth() is a wrapper around the native fetch API. It:
- Automatically adds the
Authorization: Bearer <token>header. - Prepends your
apiUrlto the request path. - Intercepts 401 errors to attempt a silent token refresh.
- Retries the request if refresh succeeds, or logs the user out if it fails.
const { fetch } = useAuth();
const loadData = async () => {
try {
// Requests http://localhost:5129/api/dashboard-data
const data = await fetch("/dashboard-data");
console.log(data);
} catch (err) {
console.error("Failed to load data", err);
}
};Changes
2026-03-04 - v1.2.0 - Audit Fixes & Hardening
- GUID Alignment: Changed
User.idfromnumbertostringto match backend GUIDs. - DTO Sync: Added missing fields (
username,phoneNumber,emailConfirmed, etc.) toUser. - Registration: Aligned
RegisterRequestfields with backend. - Security: Added
returnUrlsanitization inloginWithGoogle.
2026-03-04 - v1.1.0 - Security Hardening
- Added
errorsobject toAuthResultfor field-specific validation. - Improved
apiFetchto parse standard ASP.NETValidationProblem. - Sanitized
returnUrlin Google login.
