AuthCore
Production-ready authentication for Next.js in minutes. Complete UI components, multi-tenant policies, enterprise security, and 2FA - all customizable source code.
📚 Complete Documentation | 🚀 Quick Start | 📝 Changelog
Quick Start
# Install package
npm install codalware-auth
# Interactive setup wizard (RECOMMENDED - truly zero config!)
npx authcore init --interactive
# The wizard will:
# ✓ Detect your Next.js setup automatically
# ✓ Offer SQLite for instant dev (no database setup needed!)
# ✓ Configure auth provider (NextAuth or Better-Auth)
# ✓ Generate .env with secure defaults
# ✓ Run migrations automatically
# ✓ Create admin user
# ✓ Ready in 2 minutes!That's it! Start building:
import { AuthForm } from 'codalware-auth';
<AuthForm
mode="login"
onSuccess={(user) => router.push('/dashboard')}
/>AuthCore — concise
Production-ready authentication for Next.js with components, hooks, and optional template generators.
Current version: 3.4.12
Install:
npm install codalware-authQuick links:
- Docs: https://authcore-liard.vercel.app/
- Changelog: ./CHANGELOG.md
Notes:
- The package supports three template modes (standard, main, full).
- This release (3.4.12) rebuilds the template copy script for deterministic scaffolding, applies consistent import rewrites, and refreshes the generated README and
.env.exampleguidance for every run.
For full usage and examples see the docs site.
OrganizationSwitcher- Multi-tenant selectorSecuritySettings- Enterprise security controls- 30+ components →
🪝 React Hooks
useAuth,useLogin,useRegisteruseTwoFactor,useMagicLinkuseUserProfile,useAuditLogs- All hooks →
🔒 Enterprise Security
- Account lockout & rate limiting
- Email allowlist/blocklist
- Password policies & strength validation
- Session management & device tracking
- User enumeration protection
- Security features →
📡 Complete API
- Authentication endpoints (login, register, 2FA, magic links)
- Organization management
- Waitlist & billing webhooks
- API reference →
Key Features
✅ Zero Configuration - Interactive wizard with SQLite default
✅ Template Generator - All code copied to YOUR project, fully editable
✅ Update Management - check-updates and diff commands
✅ Multi-Tenant - Organizations, teams, custom domains
✅ Passwordless - Magic links, email OTP
✅ 2FA/MFA - TOTP authenticator apps
✅ Modern UI - Glassmorphism, dark mode, responsive
✅ i18n Ready - English & French included
✅ Type-Safe - Full TypeScript support
What's New in v3.4.12 🎉
Template copier reboot + deterministic scaffolding
Highlights:
- ✅ Rebuilt
scripts/copy-full-template.jsas a lean ESM utility that centralizes directory copying, alias-aware import rewrites, and router detection. - ✅ Supplementary assets (
config,locales,styles,prisma, and root config files) now go through the same transform pipeline, eliminating lingeringcodalware-authimports after generation. - ✅ Template README and
.env.examplefiles regenerate per mode, so dev teams always receive up-to-date instructions when re-running the copier.
Impact: Both main and full template modes now produce clean projects with correct imports, fresh documentation, and zero duplicate script content.
Tested: ✅ npm run lint at the package root. (Run the template copier in a throwaway Next.js app to validate your target mode before publishing.)
CLI Commands
# Setup
npx authcore init --interactive # Interactive wizard (recommended)
npx authcore init --template-mode=main --migrate --theme # Automated
# Database
npx authcore migrate # Run migrations
npx authcore studio # Open Prisma Studio
# Testing
npx authcore verify # Test auth endpoints
npx authcore status # Check setup status
# Updates
npx authcore check-updates # Check for new versions
npx authcore diff # Compare your changes
# Maintenance
npx authcore rollback # Remove generated files
npx authcore admin:create # Create admin user
Documentation
Requirements
- Node.js 18+ | Next.js 13+ | React 18+
- Prisma 5+ or Drizzle ORM
- NextAuth 4.24+ OR Better-Auth 0.1+
Support
- 📖 Documentation
- 📦 NPM Package
- 🐛 Issues: Check documentation or review examples
Current version: 3.4.12 (October 26, 2025)
Released under the MIT License.
Zero-Configuration Quick Start
npm install codalware-auth
# Interactive setup wizard (RECOMMENDED - truly zero config!)
npx authcore init --interactive
# The wizard will:
# Detect your Next.js setup automatically
# Offer SQLite for instant dev (no database setup needed!)
# Configure auth provider (NextAuth or Better-Auth)
# Generate .env with secure defaults
# Run migrations automatically
# Create admin user with password
# Install components and routes
# Ready in 2 minutes!
# Or use command-line flags for CI/CD
npx authcore init --template-mode=full --migrate --with-api=app --seed-admin --theme -yThree Setup Modes
Interactive Mode (Zero Config - RECOMMENDED)
npx authcore init --interactive- Truly zero configuration needed
- SQLite by default (no database setup!)
- Guides you through every option
- Auto-generates secure .env
- Creates admin user automatically
- Production-ready in minutes
MAIN TEMPLATE MODE
npx authcore init --template-mode=main- AuthCore becomes your primary source code - complete source tree copied
- All files from
src/(adapters, auth, components, hooks, config, email, i18n, lib, types, utils, validation, pages, app) - Files copied directly to
src/components/,src/hooks/,src/auth/,src/lib/, etc. - Import from
@/components,@/hooks,@/auth,@/lib(no subdirectories) - Complete ownership - modify everything as your main codebase
- 157+ source files with all dependencies and imports wired up
- Perfect for: Projects where AuthCore IS the application
FULL TEMPLATE MODE
npx authcore init --template-mode=full- Copies ALL source code to your project
- Import from
@/components/authcoreinstead ofcodalware-auth - Modify any component, hook, or logic file
- No dependency on the package (optional to keep for updates)
- Perfect for: Custom designs, unique workflows, full control
Standard Mode
npx authcore init- Imports components from
codalware-auth - Smaller project size
- Easier updates via npm
- Perfect for: Quick setup, standard flows
The CLI scaffolds Prisma schema, API routes, server actions, adapters, and environment templates. Configure .env, run migrations, and you're ready to launch. Use npx authcore rollback to cleanly remove generated files.
Choosing Your Auth Provider
AuthCore supports two production-ready authentication providers. Choose the one that fits your needs:
NextAuth.js (Stable & Battle-Tested)
npx authcore init --auth-provider=nextauth --with-api=app- Mature & Stable - Used by thousands of production apps
- 50+ Social Providers - Google, GitHub, Twitter, Discord, etc.
- Extensive Documentation - Large community & ecosystem
- Enterprise Ready - Battle-tested in production
- JWT & Database Sessions - Flexible session management
Best for: Production apps, enterprises, extensive OAuth requirements
Better Auth (Modern & Type-Safe)
npx authcore init --auth-provider=better-auth --with-api=app- Modern TypeScript - Fully type-safe, excellent DX
- Zero Configuration - Works out of the box, no placeholders
- Auto-Detection - Smart database & provider configuration
- Built-in Features - 2FA, organizations, magic links
- Smaller Bundle - Optimized for performance
Best for: New projects, TypeScript-first teams, modern stack
Interactive Setup (Let the Wizard Decide)
npx authcore init --interactiveThe interactive wizard will:
- Ask which provider you prefer
- Ask which database you want
- Auto-install required packages
- Generate provider-specific configuration
- Set up API routes automatically
- Configure environment variables
- No manual setup needed!
What Gets Installed
NextAuth Setup:
/app/api/auth/[...nextauth]/route.ts- Auth handler/lib/auth.ts- NextAuth configuration- Auto-installs:
next-auth,@next-auth/prisma-adapter
Better Auth Setup:
/app/api/auth/[...all]/route.ts- Auth handler/lib/better-auth.ts- Server configuration/lib/better-auth-client.ts- Client hooks- Auto-installs:
better-auth
Multi-Database & ORM Support
AuthCore supports 6 production-ready databases and 2 ORM options out of the box. Choose what works best for your project:
ORM Options
| ORM | Best For | Features |
|---|---|---|
| Prisma (Default) | Type-safety, Auto-migrations | Auto-complete, Schema validation, Easy migrations |
| Drizzle | Performance, SQL-like | Lightweight, SQL queries, Full TypeScript |
Database Options
| Database | Best For | Setup Time | External Service |
|---|---|---|---|
| MySQL (Default) | Production, Most reliable | 2 minutes | Required |
| PostgreSQL | Advanced features | 2 minutes | Required |
| SQLite | Development, Testing | 30 seconds | None needed |
| Neon | Serverless Postgres | 1 minute | Free tier |
| Supabase | Full Backend platform | 1 minute | Free tier |
| PlanetScale | Serverless MySQL | 1 minute | Free tier |
Zero-Config Development Setup
npx authcore init --interactive
# 1. Select ORM: "Prisma (Recommended)"
# 2. Select Database: "SQLite (Zero-config for dev)"
# 3. Select Auth: "NextAuth.js" or "Better Auth"
# No external database needed!
# Everything auto-configured!
# Start coding immediately!Production-Ready MySQL Setup (Recommended)
npx authcore init --interactive
# 1. Select ORM: "Prisma (Recommended)"
# 2. Select Database: "MySQL (Recommended for production)"
# 3. Enter your MySQL connection details
# Auto-configured with best practices!
# Connection pooling enabled!
# Optimized charset and collation!Production Setup Examples
Neon (Serverless Postgres):
npx authcore init --interactive
# Select: "Neon Serverless Postgres"
# Enter your Neon connection string from console.neon.tech
# Auto-scales with your traffic
# Connection pooling built-inSupabase (Backend-as-a-Service):
npx authcore init --interactive
# Select: "Supabase"
# Enter your Supabase connection string
# Includes realtime, storage, auth
# Dashboard for database managementPlanetScale (Serverless MySQL):
npx authcore init --interactive
# Select: "PlanetScale MySQL"
# Enter your PlanetScale connection string from app.planetscale.com
# Database branching workflow
# Non-blocking schema changesFeatures
- Auto-Detection - Prisma schema updated automatically
- Runtime Detection - Better Auth detects provider from DATABASE_URL
- Easy Migration - Start with SQLite, move to production DB anytime
- No Lock-in - Use any Prisma-supported database
- Connection Pooling - Serverless options include built-in pooling
Switching Providers
You can switch providers anytime:
```bash
# Switch to Better Auth
npx authcore init --auth-provider=better-auth --with-api=app
# Switch to NextAuth
npx authcore init --auth-provider=nextauth --with-api=appBoth providers work with all AuthCore features: 2FA, organizations, RBAC, audit logs, etc.
Highlights
- Template Generator: Scaffolds complete auth infrastructure directly into YOUR project - all code is visible and editable
- Not a Black Box: Generated code includes
// CUSTOMIZEcomments and file metadata showing update safety - Policy-aware auth forms adapt automatically when you enable magic links, enforced 2FA, email OTPs, or approval workflows
- NextAuth + Better-Auth provider abstraction with automatic detection
- Update Management: Built-in
check-updatesanddiffcommands to safely manage updates - Glassmorphism UI kit with translations, theme, and Tailwind preset included out of the box
See the documentation for feature tours, flow diagrams, and adapter guides. The doc site showcases the full step-by-step experience for modal and standalone auth surfaces, plus every toggle you can enable.
Next steps
- Follow the Quick Start: https://authcore-liard.vercel.app/getting-started/quick-start
- Review the flow gallery: https://authcore-liard.vercel.app/flows
- Track releases: https://authcore-liard.vercel.app/changelog
Released under the MIT License.
What's New in v3.4.4
CRITICAL FIX - src/ Directory Structure
Template mode now correctly respects your project's folder structure!
- Smart Detection: Automatically detects if your project uses
src/directory - Correct Placement:
- Projects WITH
src/: API routes go tosrc/app/ - Projects WITHOUT
src/: API routes go to rootapp/
- Projects WITH
- No More Errors: Prevents build failures from incorrect folder placement
- Tested: All three template modes verified with real Next.js projects
Why This Matters: Previous version could place app/ folder in wrong location, causing build errors and making API routes inaccessible. Now everything goes to the right place automatically.
✅ Standard mode: Package imports work
✅ Main template (no src/): API routes in app/
✅ Full template (with src/): API routes in src/app/
What's New in v3.4.3
Template Mode Complete - API Routes & Full Source Access
Template mode now includes ALL source files and API routes!
- Complete API Structure: Template copy now includes 14+ API route files
app/api/auth/- Login, register, magic links, 2FA verificationapp/api/organizations/- Organization managementapp/api/waitlist/- Waitlist functionalityapp/api/webhooks/- Webhook handlersapp/actions/- Server actions for auth and waitlistapp/services/- Auth adapter and type definitions
- Source Code Access:
src/folder now included in npm package for full customization - Auto-Detection: Automatically detects App Router vs Pages Router and copies appropriate structure
- Production Ready: Get a complete, working auth system with one command
- Main template mode now copies 92 files (up from 78) including all API routes
Before v3.4.3: Template mode only copied components and hooks (missing API routes)
Now: Complete authentication system with all API endpoints ready to customize
What's New in v3.4.0
Multi-ORM Security Support
All security features now work with ANY supported ORM!
Previously in v3.4.0 beta, security features only worked with Prisma. Now they work with:
- Prisma (Default)
- Drizzle
- PostgreSQL (Raw SQL)
- Appwrite
- Memory (In-memory storage)
The same adapter pattern that powers core authentication now extends to all enterprise security features. Use any ORM - the security components, APIs, and database operations automatically adapt.
Enterprise Security Features
NEW: Comprehensive security management for production applications
SecuritySettingsManager - Complete security configuration interface
- Sign-up mode control (Public, Restricted, Waitlist)
- Account lockout policies with customizable thresholds
- Password complexity requirements with strength validation
- Session timeout and concurrent session limits
- IP whitelisting and blacklisting
- MFA enforcement for administrators
- Works with any ORM - Prisma, Drizzle, PostgreSQL, Appwrite, Memory
AccountLockoutManager - Monitor and manage account security
- View all locked accounts with unlock times
- Manual unlock functionality
- Recent login attempt history with IP tracking
- Failed login reason tracking
- ORM-agnostic - Uses adapter pattern
EmailListManager - Email access control
- Email allowlist (restrict to specific emails/domains)
- Email blocklist (prevent specific emails/domains)
- Wildcard support (@domain.com)
- Easy add/remove interface
- Database-independent - Works with your chosen backend
8 New API Endpoints (All ORM-agnostic):
/api/tenant/security-settings- GET/PATCH security config/api/tenant/security/locked-accounts- View locked accounts/api/tenant/security/locked-accounts/[id]/unlock- Manual unlock/api/tenant/security/login-attempts- Login history/api/tenant/security/email-allowlist- GET/POST/DELETE/api/tenant/security/email-blocklist- GET/POST/DELETE
Enhanced Configuration:
- All security features configurable via
authcore.config.json - Environment variable support for all settings
- Auto-create defaults from config when missing
- Choose your ORM, security features adapt automatically
See the complete CHANGELOG for details.
What's New in v3.3.6
Zero-Configuration Excellence
- ** No More Placeholders**: All templates ship with production-ready values - no more "your-value-here"
- ** Smart Project Detection**: Automatically detects
src/vs root structure, places files correctly - ** Auto-Provider Setup**: Better Auth auto-installs and configures when selected
- ** Instant Setup**:
npx authcore init --interactive- truly zero configuration needed - ** No Duplicate Folders**: Fixed bug causing duplicate app/ or src/ directories
- ** Clean Code**: All linting errors resolved, duplicate functions removed
Better Auth Improvements
- Production-Ready Config: Auto-detects database provider from DATABASE_URL
- Smart Social Auth: OAuth providers auto-enable when credentials provided
- Environment Intelligence: All env variables have working defaults
- Type-Safe Throughout: Full TypeScript support with proper imports
- Comprehensive .env.example: Real values, not placeholders
Developer Experience
- Interactive Wizard: Guides through every option with smart defaults
- Clear Documentation: Updated README with provider selection guide
- Better Error Messages: Helpful output throughout installation
- One-Command Setup: From zero to production-ready in minutes
Bug Fixes
- Fixed
SyntaxError: Identifier already declaredin copy-full-template.js - Fixed duplicate function declarations
- Fixed linting error:
@typescript-eslint/no-explicit-any - Fixed project structure detection for src/ directories
- Fixed API routes placement in Next.js projects
What's New in v3.3.5
Package Exports (NPM)
Core Authentication Components - Available via npm install codalware-auth:
AuthForm- Main authentication component (login, register, password reset, 2FA)AuthModal- Modal wrapper for AuthFormPasswordInput- Password field with visibility toggleLoadingSpinner- Loading indicatorwithAuthentication- HOC for route protectionOtpInput- UI component for OTP/verification codes- All hooks, i18n, config, validation, and TypeScript types
Full Component Library - Still available via template modes:
UserProfile,ProfileDropdown,ProfileTabs- User profile managementAdminSettings- Admin dashboard componentsTwoFactorSetup- 2FA setup wizardDashboardLayout,PageLayout- Layout componentsThemeSwitcher,PasswordStrengthIndicator- UI utilities- Organization Components:
OrganizationSwitcher,CreateOrganization, etc. - Billing Components:
PricingTable,CheckoutPage, payment methods - Waitlist Components:
WaitlistFormand management - Security Components:
SecuritySettings,EmailListManager
Changes
- Removed from Source: Deleted legacy
LoginFormandRegisterForm(replaced by unifiedAuthFormin v3.0.0) - Simplified NPM Exports: Package now exports only core authentication components to reduce bundle size
- Template Modes Unchanged: All 30+ components remain available when using
--template-mode=fullor--template-mode=main
How to Access All Components
# Option 1: Full Template Mode (Recommended for customization)
npx authcore init --template-mode=full
# Copies ALL components to src/components/authcore/
# Import: import { UserProfile } from '@/components/authcore'
# Option 2: Main Template Mode
npx authcore init --template-mode=main
# Copies ALL components directly to src/components/
# Import: import { UserProfile } from '@/components'Migration Guide
If you were using LoginForm or RegisterForm from npm:
// Before (v3.3.4)
import { LoginForm, RegisterForm } from 'codalware-auth';
// After (v3.3.5)
import { AuthForm } from 'codalware-auth';
<AuthForm mode="login" />
<AuthForm mode="register" />If you need other components (Profile, Admin, Organization, Billing, Waitlist):
- Use template mode to get full source code:
npx authcore init --template-mode=full - All components work exactly as before, just accessed via local imports
What's New in v3.3.4
Release note
- Zero ESLint warnings/errors across the repository; removed all explicit
anyusages and improved TypeScript typings. - Type-safety and runtime wiring improvements to middleware, hooks, and components to ensure the package builds and ships cleanly.
Glassmorphic Auth Experience
AuthFormnow renders inside layered glass panels with gradient atmospherics, polished switcher controls, and a refined step progress bar that mirrors the documentation site aesthetic.- Social login clusters received their own frosted card so marketing pages and dashboards inherit the upgraded visual weight without extra configuration.
Password Guidance Enhancements
- The password strength indicator ships with curated gradients, requirement tracking, and actionable recommendations that surface automatically during registration flows.
- Headings and copy within the form were tuned for clarity, keeping the experience professional across light and dark modes.
Inline Password Visibility Toggle
TextInputexposes the eye icon toggle across every password field so end users can quickly confirm entries without leaving the polished UI.
What's New in v3.1.1 (archive)
README Updates & Documentation Fixes
- Fixed version inconsistencies throughout documentation
- Updated Requirements section to reflect both NextAuth and Better-Auth support
- Clarified peer dependency installation for both providers
- Corrected release date to October 16, 2025
Provider Abstraction Layer (introduced in v3.1.0)
- Choose between NextAuth or Better-Auth without changing component code
- Universal hooks API:
useSession(),useSignIn(),useSignOut()work with both providers - Better-Auth integration: Modern TypeScript-first authentication as an alternative to NextAuth
- Switch providers via
NEXT_PUBLIC_AUTH_PROVIDERenvironment variable - Zero breaking changes: Existing NextAuth implementations continue working
- Optional peer dependencies: Install only the authentication provider you need
Previous Release (v3.0)
- Component Auto-Wiring: All 84 client components + 50 server exports work immediately after installation
- Enhanced CLI: Dry-run mode, router selection, database choice, theme installation
- App Router Support: Complete templates with server actions, adapters, and typed services
- Verification Workflow:
npx authcore verifytests critical endpoints - Rollback Support: Safe file removal with manifest tracking
- Smart Templates: CUSTOMIZE comments guide schema adaptation
See the Changelog for full details.
AuthCore - Complete Authentication System
Production-ready authentication system that you can integrate in 5 minutes.
AuthCore provides everything you need for modern authentication: UI components, server logic, 2FA, email verification, account recovery, webhooks, and complete customization access.
Complete documentation: https://authcore-liard.vercel.app/
Provider Abstraction: NextAuth or Better-Auth
Choose your authentication provider without changing any component code. AuthCore v3.1.0+ introduces a unified provider abstraction layer that supports both NextAuth and Better-Auth seamlessly.
Why Provider Abstraction?
- Flexibility: Switch providers by changing one environment variable
- Modern Options: Use Better-Auth's TypeScript-first approach or stick with battle-tested NextAuth
- Smaller Bundles: Install only the provider you need as an optional peer dependency
- Easy Migration: Migrate from NextAuth to Better-Auth (or vice versa) without touching component code
- Zero Breaking Changes: Existing NextAuth implementations continue working perfectly
Quick Comparison
| Feature | NextAuth | Better-Auth |
|---|---|---|
| TypeScript | Good | Excellent (TypeScript-first) |
| Social OAuth | Full support | Full support |
| Email/Password | Via credentials | Built-in |
| Magic Links | Via email provider | Built-in |
| 2FA/MFA | Custom implementation | Built-in TOTP |
| Session Management | JWT or Database | Database sessions |
| Edge Runtime | Supported | Optimized |
| Bundle Size | Medium | Smaller |
| Maturity | Very mature | Newer, active development |
Setup with NextAuth (Default)
# 1. Install NextAuth peer dependencies
npm install next-auth @next-auth/prisma-adapter
# 2. Set provider in .env
NEXT_PUBLIC_AUTH_PROVIDER=nextauth
# 3. Use AuthCore components - they work automatically!
import { AuthForm, useSession, useSignIn } from 'codalware-auth';Setup with Better-Auth (Available in v3.1.0+)
# 1. Install Better-Auth peer dependency
npm install better-auth
# 2. Set provider in .env
NEXT_PUBLIC_AUTH_PROVIDER=better-auth
# 3. Use the SAME components - no code changes needed!
import { AuthForm, useSession, useSignIn } from 'codalware-auth';Universal Hooks API
All hooks work identically with both providers:
import { useSession, useSignIn, useSignOut } from 'codalware-auth';
function MyComponent() {
// Works with both NextAuth and Better-Auth
const { data: session, status } = useSession();
const signIn = useSignIn();
const signOut = useSignOut();
if (status === 'loading') return <Spinner />;
return (
<div>
{session ? (
<>
<p>Welcome, {session.user?.name}!</p>
<button onClick={() => signOut()}>Sign Out</button>
</>
) : (
<button onClick={() => signIn('google')}>Sign In with Google</button>
)}
</div>
);
}Social OAuth with Both Providers
Configure social providers in your auth setup:
NextAuth (pages/api/auth/[...nextauth].ts):
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import GitHubProvider from 'next-auth/providers/github';
export default NextAuth({
providers: [
GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }),
GitHubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }),
],
});Better-Auth (lib/auth.ts):
import { betterAuth } from 'better-auth';
export const auth = betterAuth({
socialProviders: {
google: { clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET },
github: { clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET },
},
});Your components (same code for both):
import { AuthForm } from 'codalware-auth';
<AuthForm
mode="login"
socialProviders={['google', 'github', 'discord']}
onSuccess={(user) => router.push('/dashboard')}
/>Migration Guide
Migrating from NextAuth to Better-Auth:
- Install Better-Auth:
npm install better-auth - Create Better-Auth configuration file
- Update environment variable:
NEXT_PUBLIC_AUTH_PROVIDER=better-auth - Restart dev server - that's it! All components continue working
No code changes required in your React components, pages, or layouts!
Technical Details
The provider abstraction uses React hooks and dynamic imports to detect which provider you're using:
- Environment Detection: Reads
NEXT_PUBLIC_AUTH_PROVIDER(defaults tonextauth) - Dynamic Loading: Imports the appropriate provider package at runtime
- Type Safety: Full TypeScript support with proper typing for both providers
- React Hooks Compliance: All hooks follow React rules - no conditional hook calls
For complete implementation details, see BETTER_AUTH_INTEGRATION.md and PROVIDER_ABSTRACTION_SUMMARY.md.
Update Management
AuthCore v3.3.3 includes powerful update management tools to keep your authentication system current:
Check for Updates
# Check if there's a new version available
npx authcore check-updates
# This shows:
# - Current version vs latest version
# - Type of update (major/minor/patch)
# - Breaking changes warnings
# - List of files you've customizedCompare Your Changes
# See all differences between your files and the template
npx authcore diff
# Compare a specific file
npx authcore diff --file app/api/auth/register/route.ts
# This shows:
# - Files you've modified
# - Line-by-line differences
# - Statistics (additions/deletions)
# - Git diff format for easy readingUnderstanding File Metadata
Files copied by AuthCore include metadata headers:
/**
* @authcore-version 3.3.3
* @authcore-safe-to-update true
* @authcore-customization-level low
*
* @customization-points
* - Email validation rules
* - Password requirements
* - Rate limiting thresholds
*/- safe-to-update:
true= safe to overwrite,false= review changes carefully - customization-level:
low/medium/highindicates expected modification frequency - customization-points: Lists common areas developers modify
Update Strategies
For Full Template Mode:
- Review changes with
npx authcore diff - Manually merge updates to customized files
- Safe-to-update files can be overwritten
- High-customization files require careful review
For Standard Mode:
- Update package:
npm install codalware-auth@latest - Component imports get new features automatically
- Review breaking changes in changelog
Features
Complete UI Components
- Pre-built login/register forms with validation and filterable social login providers
- Policy-aware auth flows that honor tenant rules (magic link vs. password, enforced 2FA, email OTP guidance) without extra wiring
- 2FA setup wizard with QR codes
- Account restoration and password reset
- User profile management
- Organization and team management
- Modern checkout page with pluggable payment methods, brandable provider logos, and a pay button that reflects the total due
- Dark mode support
- Fully responsive and accessible
- Two-factor authentication (TOTP)
- User enumeration protection
- Bot protection (Cloudflare Turnstile)
- Email restrictions (allowlist/blocklist)
- Disposable email blocking
Session and device tracking
English & French dictionaries bundled by default
registerDictionary(locale, messages)helper for custom locales- Webhook-friendly status updates secured via
AUTHCORE_CHECKOUT_SECRET - Checkout UI component ready to host Stripe Elements, Adyen Drop-in, Paddle, or manual invoicing
Quick Installation
1. Install the Package
npm install codalware-auth2. Install Required Peer Dependencies
# Core dependencies (always required)
npm install @prisma/client
npm install -D prisma
# Choose your authentication provider (install only one)
# Option A: NextAuth (default)
npm install next-auth @next-auth/prisma-adapter
# Option B: Better-Auth (alternative)
npm install better-auth
# Optional: only if you plan to send transactional emails
npm install nodemailerNote: codalware-auth automatically installs its utility dependencies (react-icons, zxcvbn, bcryptjs, etc.). Choose either NextAuth or Better-Auth as your authentication provider. The provider abstraction layer will automatically detect which one you're using via the
NEXT_PUBLIC_AUTH_PROVIDERenvironment variable.
3. Initialize AuthCore (Enhanced CLI)
The AuthCore CLI scaffolds a complete auth stack with database schema, API routes, server actions, adapters, and verification tools.
Quick Start
# Interactive setup (recommended)
npx authcore init
# Automated setup with all features
npx authcore init --migrate --with-api=app --seed-admin --theme
# Preview changes without modifying files
npx authcore init --dry-run --with-api=bothCLI Flags
| Flag | Description |
|---|---|
--yes, -y |
Accept all defaults without prompts |
--migrate |
Run database migrations automatically |
--with-api <router> |
Copy API templates: pages, app, both, or none |
--router <type> |
Choose router: app (default) or pages |
--db <type> |
Choose ORM: prisma (default), drizzle, or none |
--seed-admin |
Create super admin user after setup |
--theme |
Install AuthCore theme styles |
--no-theme |
Skip theme installation |
--dry-run |
Show what would be created without writing files |
What the CLI Creates
Core Files:
prisma/schema.prismaComplete auth database schema.env.exampleAll required environment variables (DATABASE_URL, NEXTAUTH_SECRET, SMTP, Stripe, etc.).scaffold-auth/manifest.jsonAudit trail of created files
API Routes (when using --with-api):
- App Router:
app/api/auth/*,app/api/waitlist,app/api/organizations - Pages Router:
pages/api/auth/*,pages/api/waitlist, etc. - Includes: register, login, 2FA, magic links, policy, webhooks
Server Actions (App Router only):
src/actions/auth.tsregister, login, verify, logout actionssrc/actions/waitlist.tswaitlist management
Adapters & Types:
src/services/auth/adapter.tsMap your DB models to AuthCore expectationssrc/services/auth/types.tsTypeScript definitions
Scripts:
scripts/verify-auth.jsSmoke tests for your auth endpointsscripts/undo-scaffold-auth.jsRollback generated files
CLI Commands
# Setup and initialization
npx authcore init # Interactive setup wizard
npx authcore setup # Alternative setup flow
# Database operations
npx authcore migrate # Run database migrations
npx authcore generate # Generate Prisma client
npx authcore studio # Open Prisma Studio (DB GUI)
# Testing and verification
npx authcore verify # Run smoke tests against endpoints
npx authcore verify --url=https://staging.app.com # Test remote server
npx authcore status # Check setup status
# User management
npx authcore admin:create # Create super admin user
# Maintenance
npx authcore rollback # Remove all generated files
npx authcore rollback --dry-run # Preview what would be deleted
# Update Management (Enhanced in v3.3.3)
npx authcore check-updates # Check for available updates
npx authcore diff # Show differences from templates
npx authcore diff --file=app/api/auth/register/route.ts # Diff specific file
# Styling
npx authcore styles:install # Install theme CSSVerification Workflow
After setup, verify your auth stack:
# 1. Start your dev server
npm run dev
# 2. Run verification tests
npx authcore verify
# The verify command tests:
# - POST /api/auth/register (user creation)
# - POST /api/auth/check-2fa (2FA status)
# - GET /api/auth/policy (tenant policy)
# - POST /api/waitlist (waitlist join)
# - GET /api/organizations (org listing)Rollback & Manifest
Every init creates a manifest at .scaffold-auth/manifest.json tracking all generated files and migrations. To undo:
npx authcore rollback # Interactive deletion
npx authcore rollback --dry-run # Preview onlyNote: Database migrations are NOT automatically rolled back. The rollback command will print safe instructions for reverting schema changes.
App Router Users: Generated templates include
// CUSTOMIZEcomments showing where to adapt code to your schema. The adapter pattern lets you map your existing User/Tenant models to AuthCore expectations without changing your database structure.
Template Generator Approach
AuthCore is NOT just a component library - it's a comprehensive auth template generator that scaffolds production-ready authentication code directly into your project.
Why Template Generation?
Traditional Component Libraries:
node_modules/auth-library/
hidden code you can't easily customizeAuthCore Approach:
your-project/
app/api/auth/ YOUR code, fully editable
src/services/ YOUR adapters
prisma/schema.prisma YOUR database
node_modules/codalware-auth/ Just utilitiesBenefits
- Full Visibility: All auth code is in YOUR project, not hidden in node_modules
- Complete Customization: Modify any file - add fields, change logic, integrate services
- No Lock-in: You own the code. Remove the package anytime and keep your auth working
- Easy Debugging: Set breakpoints, add logs, see exactly what's happening
- Update Control: Use
check-updatesanddiffto review changes before applying
Generated Code Includes Metadata
Every generated file has helpful metadata:
/**
* @authcore-version 3.3.3
* @authcore-safe-to-update true
* @authcore-customization-level low
*
* CUSTOMIZATION POINTS:
* - Line 45: Add custom validation
* - Line 78: Modify webhooks
*/This tells you:
- Whether the file is safe to update
- How much customization is expected
- Exactly where to add your custom logic
Update Management
# Check what's new
npx authcore check-updates
# Output:
# Update available!
# Current: 3.3.0 Latest: 3.3.3
# Changes: Security patches, new features
# Customized files: 3 detected
# See what changed
npx authcore diff
# Shows which files you've modified
# Compares with latest templates
# Safe updates
npx authcore diff --file=app/api/auth/register/route.ts
# Review specific file changes before updatingComponent Auto-Wiring
All AuthCore components automatically connect to your APIs, server actions, email flows, and auth policies after installation. No manual wiring required!
What Gets Auto-Wired
Client Components (84 exports from
codalware-auth):AuthForm,LoginForm,RegisterFormCall/api/auth/policyand render forms based on tenant rulesTwoFactorSetup,TwoFactorVerifyWire to/api/auth/2fa/*endpointsWaitlistFormPosts to/api/waitlistCreateOrganizationCalls/api/organizationsUserProfile,ProfileDropdown,DashboardLayoutUse session context automatically- All hooks:
useAuth,useLogin,useRegister,useMagicLink,useTwoFactor,useAuthPolicy
Server Functions (50 exports from
codalware-auth/server):AuthService,TenantService,TwoFactorServiceUsed in API routes and server actions- Middleware:
withAuth,withTenant,requireAdmin,protectedRoute - Utils:
TokenUtils,PasswordUtils, email service
API Routes & Actions (generated by CLI):
- App Router:
app/api/auth/*routes +src/actions/auth.tsserver actions - Pages Router:
pages/api/auth/*routes - All routes import from
codalware-auth/serverand work immediately
- App Router:
Email Flows:
- Verification emails, magic links, password reset Use
emailServicefrom server package - Templates use your
EMAIL_FROMand SMTP config from.env
- Verification emails, magic links, password reset Use
Auth Policies:
- Components call
GET /api/auth/policyReturns tenant-specific rules - Forms adapt UI based on:
requiresMagicLink,enforces2FA,requiresEmailVerification, etc. - No prop drilling or manual config
- Components call
How It Works
// 1. Install and init
npm install codalware-auth
npx authcore init --with-api=app
// 2. Import and use - components auto-connect!
import { AuthForm, useAuth } from 'codalware-auth';
function LoginPage() {
const { user, loading } = useAuth(); // Automatically uses NextAuth session
return (
<AuthForm
mode="login"
onSuccess={(user) => router.push('/dashboard')}
// Component automatically:
// - Fetches /api/auth/policy
// - Shows/hides password/magic link based on tenant
// - Handles 2FA if enforced
// - Sends verification emails
/>
);
}
// 3. Server actions work too (App Router)
import { loginAction } from '@/actions/auth'; // Generated by CLI
async function handleLogin(formData: FormData) {
const result = await loginAction(formData);
if (result.success) {
// Auto-wired with AuthService from codalware-auth/server
}
}Verification
After installation, verify everything is wired correctly:
npm run dev
npx authcore verify
# Output:
# POST /api/auth/register - 200 OK
# POST /api/auth/check-2fa - 200 OK
# GET /api/auth/policy - 200 OK
# POST /api/waitlist - 200 OK
# GET /api/organizations - 200 OKCustomization
While components auto-wire, you can still customize behavior:
// Override policy fetching
<AuthForm
customPolicyUrl="/custom-policy-endpoint"
mode="login"
/>
// Use your own API endpoints
<WaitlistForm
apiEndpoint="/api/v2/waitlist"
/>
// Fully custom components with exported hooks
import { useLogin } from 'codalware-auth';
function CustomLogin() {
const { login, isLoading, error } = useLogin();
// Build your own UI using the hook
}See Component Documentation for all props and customization options.
Environment variables overview
# Database
# DATABASE_URL=postgresql://...
# Email (choose SMTP or provider helpers)
EMAIL_SERVER_HOST="smtp.gmail.com"
EMAIL_SERVER_PORT="587"
EMAIL_FROM="AuthCore <noreply@yourapp.com>"
# Auth
NEXTAUTH_URL="http://localhost:3000"
# Billing (optional)
# BILLING_WEBHOOK_SECRET=...Need deeper guidance? Follow the dedicated Email Setup guide for step-by-step SMTP troubleshooting, deployment tips, and examples for Gmail, Resend, and other providers.
5. Import the Theme & Start Using Components
// app/layout.tsx or pages/_app.tsx
import 'codalware-auth/styles/theme.css'
import { AuthForm, CreateOrganization } from 'codalware-auth'
export default function LoginPage() {
return (
<div className="space-y-10">
<AuthForm
mode="login"
onSuccess={(user) => console.log('Logged in:', user)}
/>
<CreateOrganization
onOrganizationCreate={(org) => console.log('New org:', org)}
/>
</div>
)
}Note: The post-install script injects the theme import automatically. If your entry file changes, re-run
npx authcore styles:installto reapply the import and Tailwind preset.
Registrations now return a step-by-step follow-up (verification emails, 2FA setup, approval messaging) so you can redirect immediately or keep the guidance inside the modal.
Configure Social Login Providers
AuthCore renders Google, GitHub, and Facebook buttons whenever social login is enabled. Control which logos appear globally via configure, or override the list for a single form.
The
AuthFormcomponent automatically calls/api/auth/policyso tenants only see the sign-in options you allow (password, magic link, authenticator, email OTP, and approval messaging) without extra plumbing.
import { configure } from 'codalware-auth'
configure({
enableSocial: true,
providerSettings: {
socialProviders: {
google: { enabled: true },
github: { enabled: true },
facebook: { enabled: false }, // remove Facebook everywhere
},
},
})Override per form using the new socialProviders prop:
<AuthForm
showSocial
socialProviders={[
'google',
{ id: 'github', label: 'GitHub' },
{ id: 'facebook', enabled: false },
]}
/>Providers marked enabled: false (or omitted entirely) are not rendered, letting you mirror whichever OAuth integrations are active in your app.
6. Accept Logo Uploads in Your API
The CreateOrganization component now includes a drag-and-drop uploader that posts a Base64 logoUrl payload. Your handler can persist the file however you like:
// app/api/organizations/route.ts (Next.js example)
import { NextResponse } from 'next/server'
export async function POST(req: Request) {
const body = await req.json()
// body.logoUrl will contain a data URL when a logo is uploaded
// Store it in S3, upload to a CDN, or keep the data URL for mock/demo environments
return NextResponse.json({
organization: {
id: crypto.randomUUID(),
name: body.name,
slug: body.slug,
logoUrl: body.logoUrl, // Base64 data URL or external URL
},
})
}Tip: The logo uploader supports drag-and-drop and file picker. The API receives a Base64 data URL in
logoUrlstore it as-is for demos, or upload to S3/CDN and save the resulting URL.
Documentation
Complete documentation and live demos:
https://authcore-liard.vercel.app/
The documentation includes:
- Getting Started Step-by-step setup for Next.js, React, and Vite
- Component Reference All UI components with live demos
- Hooks API React hooks documentation
- Configuration Environment setup, customization, and advanced options
- Security Features Account lockout, email restrictions, 2FA, and more
- Examples Next.js App Router and Pages Router implementations
- API Reference Complete API documentation (all endpoints, request/response shapes)
- Guides Custom styling, translations, multi-tenancy, and more
Quick Links
- NPM Package Install from npm
- Documentation Complete documentation with live demos
- Next.js App Router Example Modern App Router implementation
- Next.js Pages Router Example Traditional Pages Router setup
- Component Demos Live UI previews
- API Reference All endpoints and request/response shapes
What's Included
UI Components
- AuthForm - Login and register forms
- SecuritySettings - 2FA and security management
- UserProfile - User profile editor
- ProfileDropdown - User menu dropdown
- TwoFactorSetup - 2FA configuration wizard
- RestoreModal - Password reset modal
- OrganizationSwitcher - Multi-tenant organization selector
- CreateOrganization - Organization creation form
- EmailListManager - Email restriction management
- WaitlistForm - Waitlist signup form
- PricingTable - Subscription plans display
- CheckoutPage - Enterprise-grade checkout layout with dynamic payment surfaces
- AuthModal - Glassmorphic modal that wraps the authentication flow
DashboardLayout - Ready-made shell with sidebar & animated header
React Hooks
- useAuth - Authentication state
- useLogin - Login functionality
- useRegister - Registration functionality
- useTwoFactor - 2FA management
- useUserDevices - Device tracking
- useAuditLogs - Audit log access
- useUserProfile - Profile management
- usePasswordChange - Password change functionality
useMagicLink - Passwordless login flow state, sending, and verification helpers
Server Utilities
- Express middleware
- Next.js API routes (App Router and Pages Router)
- Email service integration
- Webhook handlers
- Checkout session helpers and REST endpoints
Prisma client setup
Quick Example
'use client'
import { AuthForm, useMagicLink } from 'codalware-auth'
import { useRouter } from 'next/navigation'
export default function LoginPage() {
const router = useRouter()
const { status, sendMagicLink } = useMagicLink({ tenantId: 'default' })
return (
<div className="min-h-screen flex flex-col items-center justify-center gap-6">
<AuthForm
mode="login"
onSuccess={(user) => {
console.log('User logged in:', user)
router.push('/dashboard')
}}
onError={(error) => {
console.error('Login error:', error)
}}
/>
<form
onSubmit={async (event) => {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const email = formData.get('email') as string
await sendMagicLink({ email })
}}
className="flex w-full max-w-sm flex-col gap-2"
>
<input
name="email"
type="email"
placeholder="Or request a magic link"
required
className="rounded border border-gray-300 px-3 py-2"
/>
<button type="submit" disabled={status === 'sending'} className="rounded bg-blue-600 px-3 py-2 text-white">
{status === 'sent' ? 'Link sent! Check your inbox.' : 'Send magic link'}
</button>
</form>
</div>
)
}Requirements
- Node.js 18.0.0 or higher
- Next.js 13.0.0 or higher
- React 18.0.0 or higher
- Prisma 5.0.0 or higher
- Authentication Provider (choose one):
- NextAuth.js 4.24.0 or higher (default)
- Better-Auth 0.1.0 or higher (alternative)
- Import
styles/authcore-theme.cssonce in your application (copied automatically by the installer)
Examples
Complete implementation guides with step-by-step instructions:
- Next.js App Router - Modern App Router with Server Components, middleware, and streaming
- Next.js Pages Router - Traditional Pages Router with getServerSideProps and API routes
Both examples include:
- Complete authentication flow (login, register, password reset)
- Protected routes and middleware
- 2FA setup and management
- User profile and security settings
- Full TypeScript support
Support
- Documentation: https://authcore-liard.vercel.app/
- NPM Package: codalware-auth
For enterprise support, custom integrations, or questions, please visit the documentation site.
Current version: 3.4.12