npm package: @jutech-auth/nextjs-sdk
Description: Next.js authentication SDK with SSR support
Author: JuTech Devs Team
Latest version: 2.1.8

# AuthFlow Next.js SDK

A comprehensive authentication SDK for Next.js applications with full SSR support, Server Components, App Router compatibility, and advanced features like billing, organizations, and feature gating.

## 🚀 Features

- 🔐 **Complete Authentication** - JWT-based auth with automatic refresh
- 🌐 **Full SSR Support** - Server Components and App Router compatible
- 🛡️ **Advanced Protection** - Role-based access control and feature gating
- 💳 **Billing Integration** - Subscription management and usage tracking
- 🏢 **Organizations** - Multi-tenant organization support
- 📱 **Multiple Auth Methods** - Email/password, OAuth, magic links, 2FA
- 🎨 **Customizable UI** - Fully customizable components with shadcn/ui
- 📊 **Analytics** - Built-in user analytics and event tracking
- 🔒 **Security First** - WebAuthn, session management, audit logs
- 🎯 **TypeScript** - Full TypeScript support with comprehensive types

## 📦 Installation

\`\`\`bash
npm install @auth-system/nextjs-sdk
# or
yarn add @auth-system/nextjs-sdk
# or
pnpm add @auth-system/nextjs-sdk
\`\`\`

## ⚡ Quick Start

### 1. Setup AuthProvider

\`\`\`tsx
// app/providers.tsx
'use client';

import { AuthProvider } from '@auth-system/nextjs-sdk';

export function Providers({ children }: { children: React.ReactNode }) {
  return (
    <AuthProvider
      config={{
        applicationKey: 'your-app-key', // Get from AuthFlow dashboard
        apiBaseUrl: 'https://your-authflow-instance.com/api',
        appearance: {
          theme: 'dark',
          variables: {
            colorPrimary: '#3b82f6'
          }
        }
      }}
    >
      {children}
    </AuthProvider>
  );
}
\`\`\`

### 2. Wrap Your App

\`\`\`tsx
// app/layout.tsx
import { Providers } from './providers';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Providers>
          {children}
        </Providers>
      </body>
    </html>
  );
}
\`\`\`

## 🔐 Authentication Components

### Drop-in Authentication

\`\`\`tsx
// app/sign-in/page.tsx
import { SignIn } from '@auth-system/nextjs-sdk';

export default function SignInPage() {
  return (
    <div className="flex items-center justify-center min-h-screen">
      <SignIn 
        redirectUrl="/dashboard"
        appearance={{ theme: 'dark' }}
      />
    </div>
  );
}
\`\`\`

\`\`\`tsx
// app/sign-up/page.tsx
import { SignUp } from '@auth-system/nextjs-sdk';

export default function SignUpPage() {
  return (
    <div className="flex items-center justify-center min-h-screen">
      <SignUp 
        redirectUrl="/onboarding"
        appearance={{ theme: 'dark' }}
      />
    </div>
  );
}
\`\`\`

### Custom Forms

\`\`\`tsx
// Custom login with your own UI
'use client';

import { LoginForm, ForgotPasswordForm } from '@auth-system/nextjs-sdk';

export default function CustomLoginPage() {
  return (
    <div className="max-w-md mx-auto">
      <LoginForm
        onSuccess={() => router.push('/dashboard')}
        appearance={{
          elements: {
            card: 'bg-white shadow-lg',
            headerTitle: 'text-2xl font-bold'
          }
        }}
      />
      <ForgotPasswordForm className="mt-4" />
    </div>
  );
}
\`\`\`

## 🛡️ Protection & Access Control

### Route Protection

\`\`\`tsx
// app/dashboard/page.tsx
import { Protect } from '@auth-system/nextjs-sdk';

export default function DashboardPage() {
  return (
    <Protect
      role="admin"
      fallback={<div>Access denied</div>}
      redirectTo="/sign-in"
    >
      <AdminDashboard />
    </Protect>
  );
}
\`\`\`

### Conditional Rendering

\`\`\`tsx
'use client';

import { SignedIn, SignedOut, UserButton } from '@auth-system/nextjs-sdk';

export default function Header() {
  return (
    <header className="flex justify-between items-center p-4">
      <h1>My App</h1>
      <SignedIn>
        <UserButton 
          menuItems={[
            { label: 'Dashboard', url: '/dashboard' },
            { label: 'Settings', url: '/settings' }
          ]}
        />
      </SignedIn>
      <SignedOut>
        <SignInButton mode="modal" />
      </SignedOut>
    </header>
  );
}
\`\`\`

## 💳 Billing & Subscriptions

### Feature Gating

\`\`\`tsx
'use client';

import { FeatureGuard, useFeature, usePlan } from '@auth-system/nextjs-sdk';

export default function PremiumFeature() {
  const { hasFeature } = useFeature();
  const { plan, upgrade } = usePlan();

  return (
    <FeatureGuard
      feature="advanced-analytics"
      fallback={
        <div className="p-4 border rounded">
          <h3>Premium Feature</h3>
          <p>Upgrade to {plan?.name} to access advanced analytics</p>
          <button onClick={() => upgrade('pro')}>
            Upgrade Now
          </button>
        </div>
      }
    >
      <AdvancedAnalytics />
    </FeatureGuard>
  );
}
\`\`\`

### Usage Tracking

\`\`\`tsx
'use client';

import { useUsage } from '@auth-system/nextjs-sdk';

export default function APIUsage() {
  const { usage, trackUsage, isLimitReached } = useUsage();

  const handleAPICall = async () => {
    if (isLimitReached('api-calls')) {
      alert('API limit reached. Please upgrade your plan.');
      return;
    }

    // Make API call
    await fetch('/api/data');
    
    // Track usage
    await trackUsage('api-calls', 1);
  };

  return (
    <div>
      <p>API Calls: {usage['api-calls']?.current} / {usage['api-calls']?.limit}</p>
      <button onClick={handleAPICall}>Make API Call</button>
    </div>
  );
}
\`\`\`

## 🏢 Organizations

### Organization Management

\`\`\`tsx
'use client';

import { 
  OrganizationSwitcher, 
  CreateOrganization,
  useOrganization 
} from '@auth-system/nextjs-sdk';

export default function OrganizationHeader() {
  const { organization, members, inviteUser } = useOrganization();

  return (
    <div className="flex items-center gap-4">
      <OrganizationSwitcher />
      <CreateOrganization>
        <button>New Organization</button>
      </CreateOrganization>
      
      {organization && (
        <div>
          <h2>{organization.name}</h2>
          <p>{members.length} members</p>
          <button onClick={() => inviteUser('user@example.com', 'member')}>
            Invite User
          </button>
        </div>
      )}
    </div>
  );
}
\`\`\`

## 📊 Analytics & Tracking

\`\`\`tsx
'use client';

import { useAnalytics } from '@auth-system/nextjs-sdk';

export default function AnalyticsExample() {
  const { track, identify } = useAnalytics();

  const handlePurchase = (productId: string, amount: number) => {
    track('purchase', {
      productId,
      amount,
      currency: 'USD'
    });
  };

  const handleSignup = (userId: string) => {
    identify(userId, {
      plan: 'free',
      source: 'website'
    });
    
    track('user_signed_up', {
      method: 'email'
    });
  };

  return (
    <div>
      <button onClick={() => handlePurchase('prod_123', 29.99)}>
        Buy Product
      </button>
    </div>
  );
}
\`\`\`

## 🔧 Hooks Reference

### Authentication Hooks

\`\`\`tsx
const { 
  user,           // Current user object
  isLoaded,       // Auth state loaded
  isSignedIn,     // User signed in
  login,          // Login function
  logout,         // Logout function
  register        // Register function
} = useAuth();
\`\`\`

### Feature & Billing Hooks

\`\`\`tsx
const { hasFeature, checkFeature } = useFeature();
const { plan, usage, upgrade } = usePlan();
const { trackUsage, isLimitReached } = useUsage();
\`\`\`

### Organization Hooks

\`\`\`tsx
const { 
  organization,   // Current organization
  members,        // Organization members
  inviteUser,     // Invite new member
  switchOrg       // Switch organization
} = useOrganization();
\`\`\`

### Utility Hooks

\`\`\`tsx
const { track, identify } = useAnalytics();
const { notifications, markAsRead } = useNotifications();
const { applications, switchApp } = useApplications();
\`\`\`

## 🎨 Customization

### Appearance Customization

\`\`\`tsx
<AuthProvider
  config={{
    applicationKey: 'your-key',
    appearance: {
      theme: 'dark',
      variables: {
        colorPrimary: '#3b82f6',
        colorBackground: '#0f172a',
        colorText: '#f8fafc',
        borderRadius: '0.5rem'
      },
      elements: {
        card: 'shadow-2xl border-slate-700',
        headerTitle: 'text-2xl font-bold text-blue-400',
        formButtonPrimary: 'bg-blue-600 hover:bg-blue-700'
      }
    }
  }}
>
\`\`\`

### Custom Components

\`\`\`tsx
// Override default components
<LoginForm
  appearance={{
    elements: {
      card: 'bg-gradient-to-br from-blue-50 to-indigo-100',
      headerTitle: 'text-3xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent'
    }
  }}
  customFields={[
    {
      name: 'company',
      label: 'Company',
      type: 'text',
      required: true
    }
  ]}
/>
\`\`\`

## 🔒 Security Features

### Two-Factor Authentication

\`\`\`tsx
'use client';

import { TwoFactorForm, useAuth } from '@auth-system/nextjs-sdk';

export default function TwoFactorPage() {
  const { user } = useAuth();

  return (
    <div>
      {user?.twoFactorEnabled ? (
        <TwoFactorForm onSuccess={() => router.push('/dashboard')} />
      ) : (
        <div>
          <h2>Enable Two-Factor Authentication</h2>
          <button onClick={() => enableTwoFactor()}>
            Enable 2FA
          </button>
        </div>
      )}
    </div>
  );
}
\`\`\`

### Session Management

\`\`\`tsx
'use client';

import { SessionManager, useSessions } from '@auth-system/nextjs-sdk';

export default function SecurityPage() {
  const { sessions, revokeSession } = useSessions();

  return (
    <div>
      <h2>Active Sessions</h2>
      <SessionManager
        onRevokeSession={(sessionId) => revokeSession(sessionId)}
        showDeviceInfo={true}
      />
    </div>
  );
}
\`\`\`

## 🌐 Server-Side Rendering

### Server Components

\`\`\`tsx
// app/dashboard/page.tsx
import { createServerAuth } from '@auth-system/nextjs-sdk';

const serverAuth = createServerAuth({
  applicationKey: process.env.AUTHFLOW_APPLICATION_KEY!
});

export default async function DashboardPage() {
  const user = await serverAuth.getUser();
  
  if (!user) {
    redirect('/sign-in');
  }

  return (
    <div>
      <h1>Welcome, {user.name}</h1>
      <UserStats userId={user.id} />
    </div>
  );
}

async function UserStats({ userId }: { userId: string }) {
  const stats = await serverAuth.getUserStats(userId);
  
  return (
    <div>
      <p>Login count: {stats.loginCount}</p>
      <p>Last login: {stats.lastLogin}</p>
    </div>
  );
}
\`\`\`

### Middleware Protection

\`\`\`tsx
// middleware.ts
import { authMiddleware } from '@auth-system/nextjs-sdk/middleware';

export default authMiddleware({
  applicationKey: process.env.AUTHFLOW_APPLICATION_KEY!,
  publicRoutes: ['/'],
  protectedRoutes: ['/dashboard(.*)'],
  afterAuth: (auth, req) => {
    // Custom logic after auth
    if (!auth.userId && req.nextUrl.pathname.startsWith('/dashboard')) {
      return NextResponse.redirect(new URL('/sign-in', req.url));
    }
  }
});

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
\`\`\`

## 📱 Multi-Application Support

\`\`\`tsx
'use client';

import { useApplications } from '@auth-system/nextjs-sdk';

export default function AppSwitcher() {
  const { applications, currentApp, switchApplication } = useApplications();

  return (
    <select 
      value={currentApp?.id} 
      onChange={(e) => switchApplication(e.target.value)}
    >
      {applications.map(app => (
        <option key={app.id} value={app.id}>
          {app.name}
        </option>
      ))}
    </select>
  );
}
\`\`\`

## 🔧 Configuration

### Environment Variables

\`\`\`env
# Required
AUTHFLOW_APPLICATION_KEY=your_application_key_here

# Optional
NEXT_PUBLIC_AUTHFLOW_API_URL=https://your-instance.authflow.com/api
AUTHFLOW_WEBHOOK_SECRET=your_webhook_secret
\`\`\`

### Advanced Configuration

\`\`\`tsx
<AuthProvider
  config={{
    applicationKey: process.env.NEXT_PUBLIC_AUTHFLOW_APPLICATION_KEY!,
    apiBaseUrl: process.env.NEXT_PUBLIC_AUTHFLOW_API_URL,
    
    // Session configuration
    sessionTimeout: 30 * 60 * 1000, // 30 minutes
    refreshThreshold: 5 * 60 * 1000, // 5 minutes before expiry
    
    // Feature flags
    features: {
      organizations: true,
      billing: true,
      analytics: true,
      twoFactor: true
    },
    
    // Appearance
    appearance: {
      theme: 'dark',
      layout: 'card', // 'card' | 'modal' | 'inline'
      showBranding: true
    },
    
    // Callbacks
    callbacks: {
      onSignIn: (user) => console.log('User signed in:', user),
      onSignOut: () => console.log('User signed out'),
      onError: (error) => console.error('Auth error:', error)
    }
  }}
>
\`\`\`

## 📚 Component Reference

### Authentication Components
- `<SignIn />` - Complete sign-in flow
- `<SignUp />` - Complete sign-up flow  
- `<LoginForm />` - Login form only
- `<RegisterForm />` - Registration form only
- `<ForgotPasswordForm />` - Password reset form
- `<ResetPasswordForm />` - New password form
- `<TwoFactorForm />` - 2FA verification form
- `<MagicLinkForm />` - Magic link form

### User Components
- `<UserButton />` - User menu dropdown
- `<UserProfile />` - Complete user profile
- `<ProfileForm />` - Profile editing form

### Control Components
- `<SignedIn />` - Render when signed in
- `<SignedOut />` - Render when signed out
- `<Protect />` - Role/permission protection
- `<FeatureGuard />` - Feature-based protection
- `<AuthFlowLoaded />` - Render when auth loaded
- `<AuthFlowLoading />` - Render while loading

### Organization Components
- `<OrganizationSwitcher />` - Organization selector
- `<CreateOrganization />` - Organization creation
- `<OrganizationProfile />` - Organization settings

### Button Components
- `<SignInButton />` - Sign in trigger
- `<SignUpButton />` - Sign up trigger  
- `<SignOutButton />` - Sign out trigger

## 🚀 Migration Guide

### From Clerk

AuthFlow SDK is designed to be a drop-in replacement for Clerk:

\`\`\`tsx
// Before (Clerk)
import { ClerkProvider, SignIn, UserButton } from '@clerk/nextjs';

// After (AuthFlow)
import { AuthProvider, SignIn, UserButton } from '@auth-system/nextjs-sdk';
\`\`\`

Most components have the same API, making migration straightforward.

## 🤝 Support

- 📖 [Documentation](https://docs.authflow.com)
- 💬 [Discord Community](https://discord.gg/authflow)
- 🐛 [GitHub Issues](https://github.com/authflow/nextjs-sdk/issues)
- 📧 [Email Support](mailto:support@authflow.com)

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

---

**Secured by AuthFlow** 🔒