A production-ready authentication backend built with Clean Architecture, Domain-Driven Design (DDD), and Test-Driven Development (TDD) principles, featuring JWT authentication, two-factor authentication, password recovery, and comprehensive logging.
This project demonstrates modern software architecture patterns and security best practices for authentication systems. It implements a complete authentication backend with advanced features like two-factor authentication, password recovery, health monitoring, and structured logging.
Note: This project serves as a comprehensive reference implementation. While production-ready in architecture, evaluate and adapt the patterns to your specific use case rather than copying directly.
- β JWT-based authentication with access and refresh tokens
- β Two-Factor Authentication (2FA) with TOTP (Google Authenticator compatible)
- β Password recovery with time-limited, single-use tokens
- β Email and SMS verification (adapter pattern for multiple providers)
- β Backup codes for 2FA recovery
- β Password hashing with bcrypt
- β Health check endpoint with database connectivity monitoring
- β Comprehensive logging system with Winston (HTTP requests, errors, debug)
- β Clean Architecture with dependency injection
- β Database abstraction layer (supports SQL, NoSQL, In-Memory)
- β ULID-based IDs (sortable, timestamp-based)
- β Automated testing with 95+ unit and integration tests
- β Daily log rotation with 30-day retention
- β TypeScript with strict typing
- β Path aliases for clean imports
- β Hot reload in development
- β Comprehensive API documentation
- β Test coverage reporting
This project follows Clean Architecture principles with clear separation of concerns:
src/
βββ domain/ # Business logic (entities, value objects, repository interfaces)
βββ application/ # Use cases, DTOs, provider interfaces
βββ infrastructure/ # External concerns (database, HTTP, providers)
β βββ database/ # Database adapters and repositories
β βββ http/ # Controllers, routes, middlewares
β βββ providers/ # Token, hash, email, SMS, TOTP, logging
βββ shared/ # Shared constants and utilities
Key Principles:
- Dependencies flow inward (Infrastructure β Application β Domain)
- Domain layer has zero dependencies on outer layers
- Interfaces defined by inner layers, implemented by outer layers
- Easy to swap implementations (e.g., in-memory DB for testing)
- Node.js 16+
- pnpm (recommended) or npm
- Git
npm install -g pnpmOr using corepack (Node.js 16.13+):
corepack enable
corepack prepare pnpm@latest --activategit clone https://github.com/Marlinsk/node-authentication-backend.git
cd node-authentication-backendpnpm installCreate a .env file in the project root by copying the example:
cp .env.example .envDATABASE_URL="file:./dev.db"
JWT_SECRET_KEY="your-secret-key-change-in-production"PASSWORD_RESET_URL="http://localhost:3000/reset-password"
PASSWORD_RESET_TOKEN_EXPIRATION_HOURS=1TOTP_ISSUER="NodeJS Authentication Backend"
TOTP_BACKUP_CODES_COUNT=10EMAIL_PROVIDER="console"
SMS_PROVIDER="console"
EMAIL_SERVICE_API_KEY=""
EMAIL_FROM="noreply@example.com"
SMS_SERVICE_API_KEY=""
SMS_FROM=""Provider Options:
console- Development mode (logs to console)sendgrid- Production email servicetwilio- Production SMS service
NODE_ENV="development"
LOG_LEVEL="info"
LOG_DIR="logs"
LOG_TO_FILE="false"Log Levels: error, warn, info, http, debug
pnpm devServer starts at http://localhost:5500
pnpm build
pnpm startpnpm test # Run all tests
pnpm test:watch # Watch mode
pnpm test:coverage # Coverage reportGET /health- Application health status (public)
POST /- Create user accountPOST /login- User authenticationGET /- List all users (protected)GET /:id- Get user by ID (protected)PUT /:id- Update user (protected)DELETE /:id- Delete user (protected)
POST /password/request- Request password resetPOST /password/reset- Reset password with token
POST /2fa/enable- Enable 2FA (protected)POST /2fa/verify- Verify 2FA token (protected)POST /2fa/verify-backup- Verify backup code (protected)DELETE /2fa/disable- Disable 2FA (protected)
POST http://localhost:5500/
Content-Type: application/json
{
"name": "Andre Haskell",
"username": "haskell",
"email": "andhaskell@gmail.com",
"password": "SecurePass123"
}POST http://localhost:5500/login
Content-Type: application/json
{
"username": "haskell",
"password": "SecurePass123"
}POST http://localhost:5500/2fa/enable
Authorization: Bearer <your-token>
Content-Type: application/json
{
"method": "totp"
}POST http://localhost:5500/password/request
Content-Type: application/json
{
"email": "andhaskell@gmail.com"
}For complete API documentation, see API_DOCUMENTATION.md
The project includes comprehensive test coverage:
pnpm test # Run all tests (95+ tests)
pnpm test:watch # Watch mode for TDD
pnpm test:coverage # Generate coverage reportTest Structure:
- Unit tests: Domain entities, value objects, use cases
- Integration tests: Repository implementations, database operations
- E2E tests: HTTP endpoints (planned)
pnpm prisma:studiopnpm prisma:migrate # Create and apply migrations
pnpm prisma:generate # Regenerate Prisma Client
pnpm prisma:push # Push schema changes
pnpm prisma:seed # Run database seedsThe application uses an adapter pattern supporting:
- In-Memory (default for development/testing)
- SQL databases (PostgreSQL, MySQL, SQLite)
- NoSQL databases (MongoDB)
Configure via DATABASE_TYPE in database config.
The application includes a comprehensive logging system powered by Winston:
- Automatic HTTP request logging (method, URL, status, duration, IP)
- Error tracking with stack traces
- Daily log rotation (30-day retention, 20MB per file)
- Separate error and combined logs
- Colorized console output in development
- JSON format for log aggregation tools
logs/
βββ error/
β βββ error-2025-12-05.log
βββ combined/
βββ combined-2025-12-05.log
Set LOG_TO_FILE="true" in .env to enable file logging in development.
In production (NODE_ENV="production"), logs are automatically saved to files.
node-authentication-backend/
βββ src/
β βββ domain/ # Core business logic
β β βββ user/
β β β βββ entities/ # User, RefreshToken, PasswordResetToken, TwoFactorAuth
β β β βββ repositories/ # Repository interfaces
β β βββ shared/
β β βββ errors/ # Domain errors
β β βββ value-objects/ # Email, Password, EntityId
β β
β βββ application/ # Application services
β β βββ use-cases/ # Business workflows
β β β βββ user/ # CRUD, authentication
β β β βββ password-reset/ # Password recovery
β β β βββ two-factor/ # 2FA operations
β β β βββ health/ # Health check
β β βββ dtos/ # Data transfer objects
β β βββ providers/ # Provider interfaces
β β
β βββ infrastructure/ # Technical implementation
β β βββ database/
β β β βββ adapters/ # SQL, NoSQL, In-Memory
β β β βββ repositories/ # Concrete implementations
β β β βββ connection/ # Database factory
β β βββ http/
β β β βββ controllers/ # HTTP handlers
β β β βββ middlewares/ # Auth, error, logger
β β β βββ routes/ # Route definitions
β β β βββ factories/ # Dependency injection
β β βββ providers/
β β βββ token/ # JWT, bcrypt
β β βββ email/ # Console, SendGrid
β β βββ sms/ # Console, Twilio
β β βββ totp/ # Speakeasy TOTP
β β βββ logger/ # Winston
β β
β βββ shared/ # Shared resources
β β βββ constants/ # HTTP status codes
β β
β βββ tests/ # Test suites
β βββ unit/ # Isolated tests
β βββ integration/ # Database tests
β
βββ .env.example # Environment template
βββ API_DOCUMENTATION.md # Complete API docs
βββ CLAUDE.md # Project guide
βββ README.md # This file
- Node.js - Runtime environment
- TypeScript - Type safety and developer experience
- Express - HTTP server framework
- Clean Architecture - Separation of concerns
- DDD - Domain-driven design principles
- TDD - Test-driven development
- Dependency Injection - Loose coupling
- JWT - JSON Web Tokens (jsonwebtoken)
- bcrypt - Password hashing
- Speakeasy - TOTP for 2FA
- ULID - Unique ID generation
- Prisma - ORM (optional)
- Adapter pattern - Database abstraction
- Winston - Structured logging
- winston-daily-rotate-file - Log rotation
- Jest - Test framework
- 95+ tests - Unit and integration coverage
- Babel - TypeScript compilation
- Nodemon - Hot reload
- ESLint - Code linting (optional)
- API_DOCUMENTATION.md - Complete API reference with examples
- CLAUDE.md - Detailed architecture guide and development instructions
Contributions are welcome! This project serves as a learning resource, and improvements are encouraged.
- Rate limiting implementation
- Real email/SMS provider implementations
- Additional test coverage
- Performance optimizations
- Documentation improvements
This project is open source and available for educational purposes.
This project demonstrates:
- Clean Architecture implementation in Node.js
- Domain-Driven Design patterns
- Test-Driven Development workflow
- Security best practices (JWT, 2FA, password reset)
- Logging and monitoring strategies
- Database abstraction and dependency injection
- TypeScript advanced features
- Always change default JWT secret in production
- Use strong password policies
- Enable 2FA for sensitive operations
- Keep dependencies updated
- Review logs regularly for suspicious activity
- Use HTTPS in production
- Implement rate limiting for authentication endpoints
Before deploying to production:
- Change
JWT_SECRET_KEYto a strong secret - Set
NODE_ENV="production" - Configure real email provider (SendGrid)
- Configure real SMS provider (Twilio)
- Set up database migrations
- Enable
LOG_TO_FILE="true" - Configure log aggregation (ELK, CloudWatch, etc.)
- Implement rate limiting
- Set up SSL/TLS certificates
- Configure CORS properly
- Review and test health check integration
- Set up monitoring and alerts
Built with β€οΈ using Clean Architecture principles
