npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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 fetch utility that automatically injects the Bearer token.
  • 🎣 Simple Hook: useAuth() hook for easy access to user data and actions.
  • 🐍 Google OAuth: GoogleLoginButton component and loginWithGoogle() 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-react

Quick 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.md section 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:

  1. Automatically adds the Authorization: Bearer <token> header.
  2. Prepends your apiUrl to the request path.
  3. Intercepts 401 errors to attempt a silent token refresh.
  4. 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.id from number to string to match backend GUIDs.
  • DTO Sync: Added missing fields (username, phoneNumber, emailConfirmed, etc.) to User.
  • Registration: Aligned RegisterRequest fields with backend.
  • Security: Added returnUrl sanitization in loginWithGoogle.

2026-03-04 - v1.1.0 - Security Hardening

  • Added errors object to AuthResult for field-specific validation.
  • Improved apiFetch to parse standard ASP.NET ValidationProblem.
  • Sanitized returnUrl in Google login.