@jutech-auth/nextjs-sdk
v2.1.8
Published
Next.js authentication SDK with SSR support
Downloads
31
Maintainers
Readme
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} ); } ```
2. Wrap Your App
```tsx // app/layout.tsx import { Providers } from './providers';
export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( {children} ); } ```
🔐 Authentication Components
Drop-in Authentication
```tsx // app/sign-in/page.tsx import { SignIn } from '@auth-system/nextjs-sdk';
export default function SignInPage() { return ( <SignIn redirectUrl="/dashboard" appearance={{ theme: 'dark' }} /> ); } ```
```tsx // app/sign-up/page.tsx import { SignUp } from '@auth-system/nextjs-sdk';
export default function SignUpPage() { return ( <SignUp redirectUrl="/onboarding" appearance={{ theme: 'dark' }} /> ); } ```
Custom Forms
```tsx // Custom login with your own UI 'use client';
import { LoginForm, ForgotPasswordForm } from '@auth-system/nextjs-sdk';
export default function CustomLoginPage() { return ( <LoginForm onSuccess={() => router.push('/dashboard')} appearance={{ elements: { card: 'bg-white shadow-lg', headerTitle: 'text-2xl font-bold' } }} /> ); } ```
🛡️ 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={Access denied} redirectTo="/sign-in" > ); } ```
Conditional Rendering
```tsx 'use client';
import { SignedIn, SignedOut, UserButton } from '@auth-system/nextjs-sdk';
export default function Header() { return ( My App <UserButton menuItems={[ { label: 'Dashboard', url: '/dashboard' }, { label: 'Settings', url: '/settings' } ]} /> ); } ```
💳 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={ Premium Feature Upgrade to {plan?.name} to access advanced analytics <button onClick={() => upgrade('pro')}> Upgrade Now } > ); } ```
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 ( API Calls: {usage['api-calls']?.current} / {usage['api-calls']?.limit} Make API Call ); } ```
🏢 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 ( New Organization
{organization && (
<div>
<h2>{organization.name}</h2>
<p>{members.length} members</p>
<button onClick={() => inviteUser('[email protected]', '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 ( <button onClick={() => handlePurchase('prod_123', 29.99)}> Buy Product ); } ```
🔧 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 ( {user?.twoFactorEnabled ? ( <TwoFactorForm onSuccess={() => router.push('/dashboard')} /> ) : ( Enable Two-Factor Authentication <button onClick={() => enableTwoFactor()}> Enable 2FA )} ); } ```
Session Management
```tsx 'use client';
import { SessionManager, useSessions } from '@auth-system/nextjs-sdk';
export default function SecurityPage() { const { sessions, revokeSession } = useSessions();
return ( Active Sessions <SessionManager onRevokeSession={(sessionId) => revokeSession(sessionId)} showDeviceInfo={true} /> ); } ```
🌐 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 ( Welcome, {user.name} ); }
async function UserStats({ userId }: { userId: string }) { const stats = await serverAuth.getUserStats(userId);
return ( Login count: {stats.loginCount} Last login: {stats.lastLogin} ); } ```
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 => ( {app.name} ))} ); } ```
🔧 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
📄 License
MIT License - see LICENSE file for details.
Secured by AuthFlow 🔒
