npm package: @idiaz-dev/react-auth
Description: Authentication library for React + Vite applications
Latest version: 0.1.2

# React Auth

A lightweight authentication library for React + Vite applications that provides a complete authentication solution.

## Features

- Email/Username + Password authentication
- Social authentication (Google, GitHub, Facebook, Twitter)
- Multi-factor authentication with OTP (using Resend)
- Global session management with zustand
- Cookie-based authentication tokens
- Automatic reauthentication
- Route protection and automatic redirection
- Built with TypeScript
- Compatible with React 18 and 19

## Installation

```bash
# Using npm
npm install @idiaz-dev/react-auth

# Install peer dependencies
npm install zustand @tanstack/react-query axios resend
```

```bash
# Using yarn
yarn add @idiaz-dev/react-auth

# Install peer dependencies
yarn add zustand @tanstack/react-query axios resend
```

```bash
# Using pnpm
pnpm add @idiaz-dev/react-auth

# Install peer dependencies
pnpm add zustand @tanstack/react-query axios resend
```

## Quick Start

```tsx
import { AuthProvider, initialize } from "@idiaz-dev/react-auth";
import App from "./App";

const authConfig = initialize({
  apiUrl: "https://your-api.com",
  providers: {
    enabled: ["credentials", "google", "github"],
    google: {
      clientId: "your-google-client-id",
      redirectUri: "https://your-app.com/auth/google/callback",
    },
    github: {
      clientId: "your-github-client-id",
      redirectUri: "https://your-app.com/auth/github/callback",
    },
  },
  mfa: {
    enabled: true,
    resendApiKey: "your-resend-api-key",
  },
});

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <AuthProvider config={authConfig}>
      <App />
    </AuthProvider>
  </React.StrictMode>
);
```

## Usage

### 1. Login Form

```tsx
import { LoginForm } from "@idiaz-dev/react-auth";

function LoginPage() {
  return (
    <div>
      <h1>Login</h1>
      <LoginForm
        redirectUrl="/dashboard"
        onSuccess={() => console.log("Login successful")}
      />
    </div>
  );
}
```

### 2. Using the Auth Hook

```tsx
import { useAuth } from "@idiaz-dev/react-auth";

function UserProfile() {
  const { session, signOut } = useAuth();

  if (session.status !== "authenticated") {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Welcome, {session.user?.name}</h1>
      <p>Email: {session.user?.email}</p>
      <button onClick={signOut}>Sign Out</button>
    </div>
  );
}
```

### 3. Protecting Routes

```tsx
import { useProtectedRoute } from "@idiaz-dev/react-auth";

function DashboardPage() {
  // This will automatically redirect to /login if not authenticated
  const { isAuthenticated, isLoading, user } = useProtectedRoute();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome to your protected dashboard, {user?.name}!</p>
    </div>
  );
}
```

## Multi-Factor Authentication

The library supports MFA with one-time passwords (OTP). When MFA is enabled, users will be prompted to enter a verification code after successful password authentication.

```tsx
import { MfaVerification } from "@idiaz-dev/react-auth";

function MfaPage() {
  return (
    <div>
      <h1>Two-Factor Authentication</h1>
      <MfaVerification
        email="user@example.com"
        onSuccess={() => console.log("MFA successful")}
        redirectUrl="/dashboard"
      />
    </div>
  );
}
```

## Social Login

```tsx
import { SocialLogin } from "@idiaz-dev/react-auth";

function LoginPage() {
  return (
    <div>
      <h1>Login</h1>
      <LoginForm />

      <div className="divider">OR</div>

      <SocialLogin providers={["google", "github"]} redirectUrl="/dashboard" />
    </div>
  );
}
```

## Configuration Options

| Option              | Description                                              | Default                                                     |
| ------------------- | -------------------------------------------------------- | ----------------------------------------------------------- |
| `apiUrl`            | The base URL for your authentication API                 | `''`                                                        |
| `tokenName`         | The name of the cookie used to store the auth token      | `'@idiaz-dev/react-auth.session-token'`                     |
| `cookieOptions`     | Options for the auth cookie (path, domain, secure, etc.) | `{ path: '/', secure: true, sameSite: 'lax', expires: 30 }` |
| `providers.enabled` | List of enabled authentication providers                 | `['credentials']`                                           |
| `mfa.enabled`       | Whether MFA is enabled                                   | `false`                                                     |
| `mfa.resendApiKey`  | Resend API key for sending OTP emails                    | `undefined`                                                 |
| `mfa.expiresIn`     | OTP expiration time in minutes                           | `10`                                                        |

## API Reference

### Hooks

- `useAuth()` - Access authentication context and methods
- `useProtectedRoute(options)` - Protect routes and handle redirects

### Components

- `AuthProvider` - Authentication provider component
- `LoginForm` - Pre-built login form component
- `MfaVerification` - MFA verification form component
- `OtpInput` - Customizable OTP input component built with [input-otp](https://github.com/guilhermerodz/input-otp)
- `SocialLogin` - Social login buttons component

### Utilities

- `getConfig()` - Get current auth configuration
- `setConfig(config)` - Update auth configuration
- `initialize(config)` - Initialize auth configuration

## License

MIT