UNPKG

@digilogiclabs/saas-factory-auth

Version:

Modern authentication package for Next.js 15+ and React 18.2+/19+ applications with React Native 0.72+ support using Supabase and Firebase

384 lines (308 loc) 9.74 kB
# @digilogiclabs/saas-factory-auth A universal authentication package supporting both Next.js web applications and React Native mobile apps. Provides a unified API for multiple authentication providers with zero-configuration setup. ## Features - 🔐 **Multi-Provider Support** - Supabase Authentication - Firebase Authentication - Auto-detection based on environment variables - 📱 **Cross-Platform** - Next.js 15+ (App Router) - React Native with Expo - React 19+ compatible - 🚀 **Complete Auth Flows** - Email/Password authentication - OAuth providers (Google, GitHub, Facebook, Twitter, Discord, Apple, Microsoft, LinkedIn, Spotify, Twitch, Slack, Notion) - Magic link (passwordless) authentication - Password reset - 🎯 **Modern Architecture** - TypeScript-first - Zustand state management - Provider factory pattern - Proper error handling with typed errors - 💾 **Session Management** - Automatic token refresh - Persistent sessions - Custom storage adapters ## Installation ```bash npm install @digilogiclabs/saas-factory-auth # or yarn add @digilogiclabs/saas-factory-auth # or pnpm add @digilogiclabs/saas-factory-auth ``` ## Requirements - Next.js 15+ or React Native with Expo - React 19+ - Either Supabase or Firebase project credentials ## Quick Start ### 1. Configure Environment Variables #### For Supabase: ```env NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key ``` #### For Firebase: ```env NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-auth-domain NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id ``` #### Optional - Explicit Provider Selection: ```env NEXT_PUBLIC_AUTH_PROVIDER=supabase # or 'firebase' ``` ### 2. Wrap Your App with AuthProvider #### Next.js App Router: ```tsx // app/layout.tsx import { AuthProvider } from '@digilogiclabs/saas-factory-auth'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body> <AuthProvider> {children} </AuthProvider> </body> </html> ); } ``` #### React Native: ```tsx // App.tsx import { AuthProvider } from '@digilogiclabs/saas-factory-auth'; export default function App() { return ( <AuthProvider> {/* Your app components */} </AuthProvider> ); } ``` ### 3. Use the Auth Hook ```tsx 'use client'; // For Next.js App Router import { useAuth } from '@digilogiclabs/saas-factory-auth'; export default function AuthExample() { const { user, loading, error, signIn, signUp, signOut, signInWithOAuth, signInWithMagicLink, resetPassword } = useAuth(); if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; if (user) { return ( <div> <p>Welcome, {user.email}!</p> <button onClick={() => signOut()}>Sign Out</button> </div> ); } return ( <div> <button onClick={() => signIn('user@example.com', 'password')}> Sign In </button> <button onClick={() => signInWithOAuth('google')}> Sign In with Google </button> </div> ); } ``` ## API Reference ### `<AuthProvider>` The main provider component that initializes authentication. ```tsx interface AuthProviderProps { children: React.ReactNode; onAuthChange?: (event: AuthEvent) => void; autoSignIn?: boolean; // Default: true } ``` ### `useAuth()` Hook Returns the complete authentication state and methods: ```tsx interface AuthStore { // State user: User | null; session: AuthSession | null; loading: boolean; error: Error | null; // Methods signIn: (email: string, password: string) => Promise<void>; signUp: (email: string, password: string) => Promise<void>; signOut: () => Promise<void>; signInWithOAuth: (provider: OAuthProvider, redirectTo?: string) => Promise<void>; signInWithMagicLink: (email: string, redirectTo?: string) => Promise<void>; resetPassword: (email: string) => Promise<void>; getUser: () => Promise<User | null>; getSession: () => Promise<AuthSession | null>; } ``` ### Types ```tsx // User object interface User { id: string; email?: string; name?: string | null; avatar?: string | null; [key: string]: any; // Additional metadata } // Session object interface AuthSession { user: User; access_token: string; refresh_token?: string; expires_at?: number; } // OAuth providers type OAuthProvider = | 'google' | 'github' | 'facebook' | 'twitter' | 'discord' | 'apple' | 'microsoft' | 'linkedin' | 'spotify' | 'twitch' | 'slack' | 'notion'; // Auth events enum AuthEvent { SIGNED_IN = 'SIGNED_IN', SIGNED_OUT = 'SIGNED_OUT', TOKEN_REFRESHED = 'TOKEN_REFRESHED', USER_UPDATED = 'USER_UPDATED', } ``` ### Error Handling The package provides typed errors for better error handling: ```tsx enum AuthErrorType { INVALID_CREDENTIALS = 'INVALID_CREDENTIALS', USER_NOT_FOUND = 'USER_NOT_FOUND', EMAIL_ALREADY_EXISTS = 'EMAIL_ALREADY_EXISTS', WEAK_PASSWORD = 'WEAK_PASSWORD', NETWORK_ERROR = 'NETWORK_ERROR', PROVIDER_ERROR = 'PROVIDER_ERROR', CONFIGURATION_ERROR = 'CONFIGURATION_ERROR', VALIDATION_ERROR = 'VALIDATION_ERROR' } // Usage const { error } = useAuth(); if (error?.type === AuthErrorType.INVALID_CREDENTIALS) { // Handle invalid credentials } ``` ## Advanced Usage ### Custom Storage (React Native) For React Native, you can provide a custom storage implementation: ```tsx import AsyncStorage from '@react-native-async-storage/async-storage'; import { AuthProvider } from '@digilogiclabs/saas-factory-auth'; const customStorage = { getItem: async (key: string) => AsyncStorage.getItem(key), setItem: async (key: string, value: string) => AsyncStorage.setItem(key, value), removeItem: async (key: string) => AsyncStorage.removeItem(key), }; // Pass to provider factory if using advanced configuration ``` ### Listen to Auth State Changes ```tsx <AuthProvider onAuthChange={(event) => { console.log('Auth event:', event); // Handle auth state changes }} > {children} </AuthProvider> ``` ### Disable Auto Sign-In ```tsx <AuthProvider autoSignIn={false}> {children} </AuthProvider> ``` ## Provider-Specific Features ### Supabase-Specific - Row Level Security (RLS) support - Realtime subscriptions compatibility - Built-in email verification flows ### Firebase-Specific - Firebase Auth UI compatibility - Firestore rules integration - Firebase Admin SDK support ## Migration Guide ### From v0.3.x to v0.4.x 1. **Update imports**: Components like `SignIn`, `SignUp`, `OAuthButtons` are no longer provided. Use the `useAuth` hook directly. 2. **Update AuthProvider usage**: Remove any configuration props, configuration is now handled via environment variables. 3. **Update auth method calls**: All methods now return promises and handle errors internally: ```tsx // Old const { data, error } = await signIn(email, password); // New try { await signIn(email, password); } catch (error) { // Handle error } ``` ## Troubleshooting ### "Auth provider not initialized" Ensure you've wrapped your app with `<AuthProvider>` at the root level. ### "Invalid Supabase URL" Check that your `NEXT_PUBLIC_SUPABASE_URL` includes the full URL with `https://`. ### Network/DNS Errors Verify your project credentials and ensure the project is not paused (for Supabase). ## Contributing We welcome contributions! Please see our [contributing guide](CONTRIBUTING.md) for details. ## Support - [GitHub Issues](https://github.com/DigiLogicLabs/saas-factory-auth/issues) - [Documentation](https://github.com/DigiLogicLabs/saas-factory-auth/wiki) ## License MIT © [DigiLogic Labs](https://github.com/DigiLogicLabs) ## Changelog ### v1.0.1 (Latest) - **🎉 Enhanced OAuth Provider Support**: Added Microsoft, LinkedIn, Spotify, Twitch, Slack, and Notion OAuth providers - **🔧 Improved TypeScript Types**: Complete rewrite of User interface with detailed profile fields, metadata support, and extended authentication state tracking - **✨ Enhanced User Experience**: Better OAuth provider UI with proper branding, icons, and colors for all supported providers - **📚 Comprehensive Role Support**: Extended UserRole type with additional built-in roles (owner, editor, viewer, contributor, manager, developer, analyst, support) - **💪 Backward Compatibility**: All changes are non-destructive and maintain full backward compatibility ### v1.0.0 - **Major Release**: Production-ready authentication package - Complete feature parity between Supabase and Firebase providers - Enhanced error handling and user feedback - Comprehensive testing and documentation ### v0.4.3 - Fixed React hooks usage in auth callbacks - Improved error handling and network error detection - Added proper auth provider initialization in store - Enhanced TypeScript types ### v0.4.0 - Complete architecture rewrite - Added Firebase support alongside Supabase - Implemented provider factory pattern - Migrated to Zustand for state management - React 19 and Next.js 15 compatibility ### v0.3.x - Initial Supabase-only implementation - Basic authentication flows - Component-based architecture