shaonu-authkit
v1.0.7
Published
CLI to scaffold a full Express + MongoDB Auth Service
Maintainers
Readme
🔐 shaonu-authkit
Production-ready Express + MongoDB Authentication Service — Zero config, fully scaffolded in seconds!
Stop building auth from scratch. Get a complete, secure authentication backend with user registration, login, logout, and password reset in one command.
📖 Table of Contents
- Quick Start
- Features
- Why shaonu-authkit?
- How It Works
- Installation & Setup
- Project Structure
- Configuration
- Usage Guide
- API Reference
- Security
- Database Setup
- Email Configuration
- Production Deployment
- Dependencies
- Contributing
- License
🚀 Quick Start
Get your authentication backend running in 2-3 minutes:
npx shaonu-authkit⚠️ Important: This is a CLI tool — do NOT use
npm i shaonu-authkit
✨ Features
- Complete Auth System — Register, Login, Logout, Forgot Password, Reset Password
- Enterprise Security — bcryptjs hashing, JWT tokens, httpOnly cookies, CSRF protection
- Email Integration — Automated password reset emails with Gmail + Nodemailer
- Production Ready — Error handling, validation, CORS, MongoDB best practices
- Zero Config — All essential packages pre-configured and tested
- CLI Wizard — Interactive setup that prevents configuration mistakes
- Fully Scaffolded — Complete project structure ready for development
❓ Why shaonu-authkit?
| Problem | Solution |
| ------------------------------------------ | -------------------------------------------- |
| Building auth from scratch takes hours | Generate complete auth system in minutes |
| Security vulnerabilities if misconfigured | Enterprise-grade security built-in |
| Manual setup is error-prone | Interactive CLI wizard prevents mistakes |
| Juggling multiple packages & versions | All dependencies pre-selected and tested |
| Complex config files to manage | Auto-generated .env and settings |
| Time to market matters | Start building features immediately |
Perfect for:
- 🚀 Startups needing a quick MVP with auth
- 👨💻 Developers who want secure auth without reinventing the wheel
- 🏢 Teams that need consistent auth implementation across projects
- 🎓 Learners who want to understand auth best practices
🔧 How It Works
When you run npx shaonu-authkit, the CLI wizard guides you through a 3-step process:
Step 1️⃣: Answer Simple Questions
? Project name: my-auth-backend
? MongoDB URI: mongodb://localhost:27017/authkit
? JWT Secret: your-super-secret-key
? Port number: 3000
? Gmail address: [email protected]
? Gmail App Password:your-app-password
?Frontend URL: http://localhost:5173Step 2️⃣: Automatic Project Generation
The CLI scaffolds your complete project with:
- ✅ Express.js server with pre-configured middleware
- ✅ MongoDB connection with Mongoose
- ✅ Complete auth controllers (Register, Login, Logout, Password Reset)
- ✅ User model with validation and security
- ✅ API routes ready to use
- ✅ Nodemailer email service integration
- ✅ Auto-generated
.envfile - ✅ All dependencies installed
Step 3️⃣: You're Ready!
cd your-project-name
npm run devServer runs on http://localhost:3000 with all endpoints ready to use!
🛠️ Installation & Setup
Prerequisites
- Node.js (v14 or higher)
- MongoDB (local or MongoDB Atlas)
- Gmail account (for password reset emails)
Quick Install
# Create your auth backend
npx shaonu-authkit
# Navigate to your project
cd your-project-name
# Start development server
npm run devAvailable Scripts
npm run dev # Start with nodemon (auto-reload)
npm start # Start production server
npm test # Run tests (if configured)📂 Project Structure
your-project/
├── src/
│ ├── config/
│ │ ├── db.js → MongoDB connection setup
│ │ └── email.js → Nodemailer configuration
│ ├── controllers/
│ │ └── user.controller.js → Auth logic (Register, Login, Logout, etc.)
│ ├── models/
│ │ └── user.model.js → User schema with validation
│ ├── routes/
│ │ └── user.route.js → API endpoint definitions
│ └── utils/
│ └── emailTemplates.js → Email template generators
│
├── app.js → Express app entry point
├── .env → Environment variables (Git ignored)
├── .gitignore → Git ignore rules
├── package.json → Project dependencies
└── README.md → Project documentation⚙️ Configuration
Environment Variables
After setup, your .env file will contain:
# Server
PORT=3000
NODE_ENV=development
CLIENT_URL=http://localhost:5173
# Database
MONGO_URI=mongodb://localhost:27017/authkit
# Authentication
JWT_SECRET=your-super-secret-key
JWT_EXPIRES_IN=7d
# Email Service
[email protected]
EMAIL_PASS=your-app-specific-passwordVariable Reference:
| Variable | Description | Example |
| ---------------- | ----------------------------------- | ----------------------------------- |
| PORT | Server port | 3000 |
| NODE_ENV | Environment mode | development / production |
| CLIENT_URL | Frontend URL for CORS | http://localhost:5173 |
| MONGO_URI | MongoDB connection string | mongodb://localhost:27017/authkit |
| JWT_SECRET | Token signing secret (min 32 chars) | your-secure-key-here |
| JWT_EXPIRES_IN | Token expiration time | 7d / 24h |
| EMAIL_USER | Gmail address | [email protected] |
| EMAIL_PASS | Gmail app password | abcd efgh ijkl mnop |
🗄️ Database Setup
MongoDB Local Setup
# 1. Install MongoDB Community Edition
# Visit: https://docs.mongodb.com/manual/installation/
# 2. Start MongoDB service
mongod
# 3. Your connection string
mongodb://localhost:27017/authkitMongoDB Atlas (Cloud Setup)
- Go to MongoDB Atlas
- Create a free account
- Create a new cluster
- Get your connection string
- Add to
.env:
MONGO_URI=mongodb+srv://username:[email protected]/authkit📧 Email Configuration
This project uses Gmail + Nodemailer for sending password reset emails.
Setup Gmail Authentication
Enable 2-Factor Authentication:
- Go to Google Account Security
- Enable 2-Step Verification
Generate App Password:
- Go to App Passwords
- Select "Mail" and "Windows Computer"
- Google will generate a 16-character password
- Copy and paste it as
EMAIL_PASSin.env
Update
.envfile:
[email protected]
EMAIL_PASS=abcd efgh ijkl mnop⚠️ Security: Never commit
.envto version control!
🚀 Usage Guide
Get Started After Setup
# 1. Navigate to your project
cd your-project-name
# 2. Install dependencies (if not done by CLI)
npm install
# 3. Start development server
npm run devYour API is now running at: http://localhost:3000
📡 API Reference
Available Endpoints
| Method | Route | Description | Auth Required |
| ------ | --------------------------------- | ------------------------- | ------------- |
| POST | /api/auth/register | Register new user | ❌ No |
| POST | /api/auth/login | Login user | ❌ No |
| POST | /api/auth/logout | Logout user | ✅ Yes |
| POST | /api/auth/forgot-password | Request password reset | ❌ No |
| POST | /api/auth/reset-password/:token | Reset password with token | ❌ No |
Register Endpoint
curl -X POST http://localhost:3000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"userName": "john_doe",
"email": "[email protected]",
"password": "SecurePass123"
}'Response (Success):
{
"success": true,
"message": "User registered successfully",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"user": {
"id": "507f1f77bcf86cd799439011",
"userName": "john_doe",
"email": "[email protected]"
}
}Login Endpoint
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "SecurePass123"
}'Logout Endpoint
curl -X POST http://localhost:3000/api/auth/logout \
-H "Authorization: Bearer YOUR_TOKEN_HERE"Forgot Password Endpoint
curl -X POST http://localhost:3000/api/auth/forgot-password \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]"
}'Response:
{
"success": true,
"message": "Password reset email sent"
}Reset Password Endpoint
curl -X POST http://localhost:3000/api/auth/reset-password/YOUR_RESET_TOKEN \
-H "Content-Type: application/json" \
-d '{
"password": "NewSecurePass456"
}'Error Response Examples
{
"success": false,
"message": "Email already exists"
}{
"success": false,
"message": "Invalid email or password"
}🔐 Security
Security Features Implemented
- ✅ Password Hashing — bcryptjs with 12 salt rounds
- ✅ JWT Tokens — Secure token-based authentication
- ✅ httpOnly Cookies — XSS protection (tokens stored in secure cookies)
- ✅ CSRF Protection — sameSite: strict cookie setting
- ✅ HTTPS Ready — Secure flag enabled in production
- ✅ Password Reset Tokens — SHA-256 hashed with 10-minute expiration
- ✅ Email Validation — Regex pattern matching
- ✅ Database Constraints — Unique email at database level
- ✅ Password Requirements — Minimum 6 characters
- ✅ CORS Protection — Configurable client URL
- ✅ Request Logging — Morgan middleware for audit trail
- ✅ Data Privacy — Passwords never returned in API responses
Best Practices Followed
- Never store passwords in plain text — Always hash with bcryptjs
- Use environment variables — Store secrets in
.env, never commit them - Validate all inputs — Email regex, password length checks
- Implement rate limiting — Prevent brute force attacks (recommended add-on)
- Use HTTPS in production — Always encrypt data in transit
- Secure headers — Use helmet.js for additional security headers (recommended)
📦 Dependencies
Core Dependencies
| Package | Version | Purpose |
| --------------- | ------- | --------------------------------- |
| express | ^5.2.1 | Web framework & routing |
| mongoose | ^9.6.3 | MongoDB ODM & validation |
| bcryptjs | ^3.0.3 | Password hashing & encryption |
| jsonwebtoken | ^9.0.3 | JWT token creation & verification |
| cookie-parser | ^1.4.7 | Cookie parsing & handling |
| cors | ^2.8.6 | Cross-origin request handling |
| dotenv | ^17.4.2 | Environment variable loading |
| morgan | ^1.10.1 | HTTP request logging |
| nodemailer | ^8.0.10 | Email service for password resets |
| nodemon | (dev) | Auto-reload on file changes |
Why These Dependencies?
- Express — Industry-standard Node.js web framework
- Mongoose — Type-safe MongoDB interactions with validation
- bcryptjs — Industry-standard password hashing
- JWT — Stateless authentication standard
- CORS — Safe cross-origin requests
- Nodemailer — Reliable email delivery
- Morgan — Essential for debugging & monitoring
🚀 Production Deployment
Pre-Deployment Checklist
- [ ] Set
NODE_ENV=production - [ ] Use a strong JWT_SECRET (min 32 random characters)
- [ ] Configure production MongoDB URI
- [ ] Setup HTTPS/SSL certificate
- [ ] Configure CLIENT_URL for your frontend domain
- [ ] Use Gmail App Password (generated password, not regular password)
- [ ] Enable secure cookies (automatic in production)
- [ ] Configure CORS settings for your frontend domain
- [ ] Setup environment variables securely on server
- [ ] Enable request logging & monitoring
- [ ] Configure database backups
- [ ] Setup error tracking (Sentry, etc.)
Deployment Platforms
Recommended platforms:
- Vercel — Serverless Node.js hosting
- Heroku — Simple cloud deployment
- Railway — Modern cloud platform
- Render — Simple cloud hosting
- AWS/GCP/Azure — Enterprise solutions
Environment Variables for Production
NODE_ENV=production
PORT=3000
MONGO_URI=mongodb+srv://user:[email protected]/authkit-prod
JWT_SECRET=your-long-random-secret-key-32-characters-minimum
JWT_EXPIRES_IN=7d
CLIENT_URL=https://your-frontend-domain.com
[email protected]
EMAIL_PASS=your-app-specific-password🐛 Troubleshooting
MongoDB Connection Issues
Error: connect ECONNREFUSED 127.0.0.1:27017Solution: Make sure MongoDB is running:
mongodEmail Not Sending
Error: Invalid login: 534-5.7.8 Application-specific password requiredSolution:
- Use Gmail App Password (not regular password)
- Enable 2-Factor Authentication on your Google Account
- Regenerate App Password
JWT Token Errors
Error: JsonWebTokenError: invalid tokenSolution:
- Ensure
JWT_SECRETis set in.env - Token must be sent in Authorization header
- Token may have expired
📝 Contributing
We welcome contributions! Here's how:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
👨💻 Author
Made with ❤️ by Shaonu
- GitHub: @shaonu
- NPM: shaonu-authkit
- Website: shaonu.dev
📄 License
This project is licensed under the MIT License — free to use in any project!
See the LICENSE file for details.
🙏 Support
Love shaonu-authkit? Show your support:
- ⭐ Give us a star on GitHub
- 📦 Use it in your projects
- 🐛 Report bugs and suggest features
- 📢 Share it with your network
Happy Coding! 🚀
