UNPKG

nodejs-fs

Version:

CLI tool to scaffold production-ready Express + Mongoose backend with security best practices

611 lines (451 loc) โ€ข 16.2 kB
<div align="center"> <h1>๐Ÿš€ nodejs-fs</h1> <p><strong>Scaffold production-ready Express + MongoDB backends in seconds</strong></p> [![npm version](https://img.shields.io/npm/v/nodejs-fs.svg?style=flat-square)](https://www.npmjs.com/package/nodejs-fs) [![npm downloads](https://img.shields.io/npm/dm/nodejs-fs.svg?style=flat-square)](https://www.npmjs.com/package/nodejs-fs) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![Node.js Version](https://img.shields.io/node/v/nodejs-fs.svg?style=flat-square)](https://nodejs.org) <p> <a href="#-quick-start">Quick Start</a> โ€ข <a href="#-features">Features</a> โ€ข <a href="#-whats-included">What's Included</a> โ€ข <a href="#-usage">Usage</a> โ€ข <a href="#-api-documentation">API Docs</a> </p> </div> --- ## ๐ŸŽฏ Why nodejs-fs? Stop wasting hours setting up the same backend infrastructure. **nodejs-fs** generates a complete, production-ready Express.js + MongoDB backend with authentication, security, and best practices baked in. **Perfect for:** - ๐Ÿƒโ€โ™‚๏ธ Hackathons and MVPs - ๐Ÿ“š Learning full-stack development - ๐ŸŽ“ Teaching backend architecture - ๐Ÿš€ Rapid prototyping - ๐Ÿ’ผ Freelance projects ## โœจ Features <table> <tr> <td width="33%" valign="top"> ### ๐Ÿ” Security First - JWT authentication - Bcrypt password hashing - Rate limiting & brute force protection - Helmet.js security headers - CORS configuration - Cookie parser </td> <td width="33%" valign="top"> ### โšก Production Ready - Express 5.x (latest) - Environment-based config - Winston logging - Global error handling - Joi validation - MongoDB connection pooling - Compression middleware </td> <td width="33%" valign="top"> ### ๐Ÿ› ๏ธ Developer Experience - Clean MVC architecture - RESTful API design - Node.js watch mode (no nodemon) - Email templates - Image upload & processing - Comprehensive documentation </td> </tr> </table> ## ๐Ÿš€ Quick Start Get your backend up and running in 60 seconds: ```bash # Create your project with npx (no installation needed) npx create-nodejs-fs my-awesome-api # Navigate to your project cd my-awesome-api # Configure environment cp .env.example .env # Edit .env with your MongoDB URI and JWT secret # Start developing npm run dev ``` **That's it!** You now have a fully-functional backend with auth, CRUD operations, and more. ๐ŸŽ‰ --- ## ๐Ÿ“ฆ Installation & Usage ### Option 1: Use with npx (Recommended) No installation required - just run: ```bash npx create-nodejs-fs my-project-name ``` ### Option 2: Install Globally ```bash npm install -g nodejs-fs create-nodejs-fs my-project-name ``` ### What Happens Next The CLI will automatically: 1. Create the project structure 2. Copy all template files 3. Install dependencies (npm install) 4. Set up your backend with all configurations ### Available Options ```bash create-nodejs-fs <project-name> [options] Options: --no-install Skip npm install --git Initialize git repository --verbose Show detailed logs -v, --version Output version number -h, --help Display help ``` ## ๐Ÿ“ What's Included ### Complete Project Structure ``` your-project/ โ”œโ”€โ”€ ๐Ÿ“‚ src/ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ config/ # Configuration files โ”‚ โ”‚ โ”œโ”€โ”€ cloudinary.js # Image hosting setup โ”‚ โ”‚ โ”œโ”€โ”€ db.js # MongoDB connection โ”‚ โ”‚ โ””โ”€โ”€ logger.js # Winston logger config โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ controllers/ # Business logic โ”‚ โ”‚ โ”œโ”€โ”€ authController.js # Auth operations โ”‚ โ”‚ โ””โ”€โ”€ productController.js # CRUD operations โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ middlewares/ # Custom middleware โ”‚ โ”‚ โ”œโ”€โ”€ auth.js # JWT verification โ”‚ โ”‚ โ”œโ”€โ”€ errorHandler.js # Global error handler โ”‚ โ”‚ โ”œโ”€โ”€ rateLimiter.js # Rate limiting โ”‚ โ”‚ โ””โ”€โ”€ validate.js # Input validation โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ models/ # Database schemas โ”‚ โ”‚ โ”œโ”€โ”€ User.js # User model + methods โ”‚ โ”‚ โ””โ”€โ”€ Product.js # Product model โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ routes/ # API routes โ”‚ โ”‚ โ”œโ”€โ”€ authRoutes.js # /api/auth/* โ”‚ โ”‚ โ”œโ”€โ”€ productRoutes.js # /api/products/* โ”‚ โ”‚ โ””โ”€โ”€ index.js # Route aggregator โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ๐Ÿ“‚ utils/ # Helper functions โ”‚ โ”‚ โ”œโ”€โ”€ imageProcessor.js # Image upload/resize โ”‚ โ”‚ โ”œโ”€โ”€ mailer.js # Email sending โ”‚ โ”‚ โ””โ”€โ”€ slugifyUtil.js # URL-friendly slugs โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ app.js # Express app configuration โ”‚ โ””โ”€โ”€ index.js # Server entry point โ”‚ โ”œโ”€โ”€ .env.example # Environment template โ”œโ”€โ”€ package.json โ””โ”€โ”€ README.md # Complete documentation ``` ### ๐Ÿ”‹ Tech Stack & Dependencies **Core Framework:** - **Express.js** `^5.1.0` - Modern, fast web framework (Express 5) - **Mongoose** `^8.x` - MongoDB object modeling **Security:** - **bcrypt** - Password hashing with salt - **jsonwebtoken** - JWT token generation & verification - **helmet** - Security HTTP headers - **express-rate-limit** - Brute force protection - **cors** - Cross-origin resource sharing **Utilities:** - **nodemailer** - Email sending (password reset, notifications) - **cloudinary** - Cloud image hosting & transformation - **sharp** - High-performance image processing - **multer** - Multipart/form-data file upload - **joi** - Schema validation & sanitization - **winston** - Comprehensive logging - **slugify** - URL-friendly string conversion - **compression** - Gzip compression middleware - **cookie-parser** - Parse cookies - **dotenv** - Environment variable management **Development:** - **Node.js** `>=18.0.0` - Built-in watch mode with `--watch` flag - **morgan** - HTTP request logger --- ## โš™๏ธ Configuration Guide ### Essential Environment Variables ```env # Server Configuration PORT=5000 # Server port NODE_ENV=development # development | production # Database MONGODB_URI=mongodb://localhost:27017/mydb # MongoDB connection string # JWT Authentication JWT_SECRET=your-256-bit-secret-key # Strong random string JWT_EXPIRE=7d # Token expiration (7d, 24h, etc.) JWT_COOKIE_EXPIRE=7 # Cookie expiration in days ``` ### Optional Features ```env # Email Service (for password reset) SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your-email@gmail.com SMTP_PASSWORD=your-app-specific-password FROM_EMAIL=noreply@yourapp.com FROM_NAME=Your App Name # Cloudinary (for image uploads) CLOUDINARY_CLOUD_NAME=your-cloud-name CLOUDINARY_API_KEY=your-api-key CLOUDINARY_API_SECRET=your-api-secret # Frontend URL (for CORS and email links) CLIENT_URL=http://localhost:3000 ``` ### Quick Setup Tips **MongoDB Options:** - ๐Ÿ–ฅ๏ธ **Local:** Install MongoDB Community Server - โ˜๏ธ **Cloud:** Use [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) (free tier available) **Email Service:** - Use Gmail with [App Password](https://support.google.com/accounts/answer/185833) - Or try [SendGrid](https://sendgrid.com/), [Mailgun](https://www.mailgun.com/), [AWS SES](https://aws.amazon.com/ses/) **Image Hosting:** - Sign up at [Cloudinary](https://cloudinary.com/) (free tier: 25GB storage, 25GB bandwidth) --- ## ๐ŸŽฏ Use Cases Perfect for building: - ๐Ÿ›๏ธ **E-commerce APIs** - Product management, user auth, order processing - ๐Ÿ“ฑ **Mobile App Backends** - REST API for iOS/Android apps - ๐Ÿ’ฌ **Social Platforms** - User profiles, posts, comments, likes - ๐Ÿ“ฐ **Blog/CMS Systems** - Content management with authentication - ๐ŸŽ“ **Learning Management** - Course platforms, student portals - ๐Ÿข **Business Applications** - CRM, inventory management, booking systems - ๐ŸŽฎ **Gaming Backends** - Player data, leaderboards, achievements --- ## ๐Ÿ›ก๏ธ Security Best Practices Our template implements enterprise-grade security: | Security Layer | Implementation | |---------------|----------------| | ๐Ÿ” **Authentication** | JWT tokens with secure secret key | | ๐Ÿ”’ **Password Storage** | Bcrypt hashing (10 salt rounds) | | ๐Ÿ›ก๏ธ **HTTP Headers** | Helmet.js (XSS, clickjacking, etc.) | | ๐Ÿšฆ **Rate Limiting** | Max 100 requests per 15 min per IP | | โœ… **Validation** | Joi schema validation on all inputs | | ๐ŸŒ **CORS** | Configurable allowed origins | | ๐Ÿช **Cookies** | HttpOnly, Secure, SameSite flags | | ๐Ÿ“ **Logging** | Winston for security audits | | ๐Ÿ—œ๏ธ **Compression** | Gzip compression for responses | --- ## ๐Ÿ“– Available Scripts ```bash npm run dev # Start with Node.js watch mode (auto-reload) npm start # Start production server ``` --- ## ๐Ÿค Contributing We welcome contributions! Here's how you can help: 1. ๐Ÿ› **Report bugs** - [Open an issue](https://github.com/iiMuhammadRashed/nodejs-fs/issues) 2. ๐Ÿ’ก **Suggest features** - Share your ideas 3. ๐Ÿ”ง **Submit PRs** - Fork, code, and create pull requests 4. โญ **Star the repo** - Show your support --- ## ๐Ÿ“„ License MIT ยฉ MERN Stack Hero Free to use for personal and commercial projects. --- ## ๐Ÿ’ฌ Support & Community Need help? We've got you covered: - ๐Ÿ“š **Documentation:** [GitHub Wiki](https://github.com/iiMuhammadRashed/nodejs-fs) - ๐Ÿ› **Bug Reports:** [GitHub Issues](https://github.com/iiMuhammadRashed/nodejs-fs/issues) - ๐Ÿ’ก **Feature Requests:** [GitHub Discussions](https://github.com/iiMuhammadRashed/nodejs-fs/discussions) - โญ **Star us on GitHub** to stay updated --- ## ๐Ÿ—บ๏ธ Roadmap Coming soon: - [ ] TypeScript template option - [ ] GraphQL API template - [ ] WebSocket support - [ ] Redis caching integration - [ ] Stripe payment integration - [ ] Social OAuth (Google, GitHub, Facebook) - [ ] Swagger/OpenAPI documentation - [ ] Docker configuration - [ ] CI/CD templates (GitHub Actions, GitLab CI) - [ ] Testing setup (Jest, Supertest) --- <div align="center"> ### โญ If nodejs-fs helped you, please star the repo! โญ **Made with โค๏ธ by [MERN Stack Hero](https://github.com/iiMuhammadRashed)** [Report Bug](https://github.com/iiMuhammadRashed/nodejs-fs/issues) ยท [Request Feature](https://github.com/iiMuhammadRashed/nodejs-fs/issues) ยท [Contribute](https://github.com/iiMuhammadRashed/nodejs-fs/pulls) </div> ## ๐Ÿ“š API Documentation ### ๐Ÿ” Authentication Endpoints | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | POST | `/api/auth/register` | Register new user | โŒ | | POST | `/api/auth/login` | Login user | โŒ | | POST | `/api/auth/forgot-password` | Request password reset | โŒ | | POST | `/api/auth/reset-password/:token` | Reset password with token | โŒ | | GET | `/api/auth/me` | Get current user profile | โœ… | ### ๐Ÿ“ฆ Product Endpoints | Method | Endpoint | Description | Auth Required | |--------|----------|-------------|---------------| | GET | `/api/products` | Get all products (paginated) | โŒ | | GET | `/api/products/:id` | Get single product | โŒ | | POST | `/api/products` | Create new product | โœ… | | PUT | `/api/products/:id` | Update product | โœ… | | DELETE | `/api/products/:id` | Delete product | โœ… | <details> <summary><strong>๐Ÿ“– Click to see API examples</strong></summary> **Register a new user:** ```bash curl -X POST http://localhost:5000/api/auth/register \ -H "Content-Type: application/json" \ -d '{ "name": "John Doe", "email": "john@example.com", "password": "securePassword123" }' ``` **Login:** ```bash curl -X POST http://localhost:5000/api/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "john@example.com", "password": "securePassword123" }' ``` **Create a product (with auth):** ```bash curl -X POST http://localhost:5000/api/products \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -d '{ "name": "Awesome Product", "description": "This is an awesome product", "price": 99.99, "category": "Electronics" }' ``` </details> ## Configuration After generating your project, create a `.env` file based on `.env.example`: ```env # Server PORT=5000 NODE_ENV=development # Database MONGODB_URI=mongodb://localhost:27017/your-database # JWT JWT_SECRET=your-super-secret-jwt-key JWT_EXPIRE=7d JWT_COOKIE_EXPIRE=7 # Email SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your-email@gmail.com SMTP_PASSWORD=your-email-password FROM_EMAIL=noreply@yourapp.com FROM_NAME=Your App Name # Cloudinary CLOUDINARY_CLOUD_NAME=your-cloud-name CLOUDINARY_API_KEY=your-api-key CLOUDINARY_API_SECRET=your-api-secret # Client URL CLIENT_URL=http://localhost:3000 ``` --- ## ๐ŸŽ“ Getting Started Guide ### Step 1: Create Your Project ```bash npx create-nodejs-fs my-awesome-api # Or if installed globally: create-nodejs-fs my-awesome-api ``` The CLI accepts a project name as an argument (no interactive prompts). **Available options:** - `--no-install` - Skip dependency installation - `--git` - Initialize git repository - `--verbose` - Show detailed logs ### Step 2: Navigate to Your Project ```bash cd my-awesome-api ``` ### Step 3: Configure Environment ```bash cp .env.example .env ``` Edit `.env` with your credentials: ```env # Minimum required configuration MONGODB_URI=mongodb://localhost:27017/your-database JWT_SECRET=your-super-secret-key-change-this PORT=5000 ``` ### Step 4: Start Developing ```bash npm run dev ``` Your API is now running at `http://localhost:5000` ๐Ÿš€ Uses Node.js built-in `--watch` flag (Node 18+) - no nodemon needed! ### Step 5: Test Your API ```bash # Health check curl http://localhost:5000 # Register a user curl -X POST http://localhost:5000/api/auth/register \ -H "Content-Type: application/json" \ -d '{"name":"Test User","email":"test@example.com","password":"password123"}' ``` --- ## ๐Ÿ“Š What You Get Out of the Box | Feature | Included | Configuration Required | |---------|----------|------------------------| | โœ… Express.js Server | โœ“ | Minimal | | โœ… MongoDB + Mongoose | โœ“ | Connection string only | | โœ… JWT Authentication | โœ“ | Secret key only | | โœ… Password Hashing | โœ“ | None | | โœ… Input Validation | โœ“ | None | | โœ… Error Handling | โœ“ | None | | โœ… Security Headers | โœ“ | None | | โœ… Rate Limiting | โœ“ | Optional tuning | | โœ… CORS | โœ“ | Optional tuning | | โœ… Email Service | โœ“ | SMTP credentials | | โœ… Image Upload | โœ“ | Cloudinary credentials | | โœ… Logging | โœ“ | None | | โœ… API Documentation | โœ“ | None | --- ## ๐Ÿ†š Why Choose nodejs-fs? <table> <tr> <th width="25%">Manual Setup</th> <th width="25%">Express Generator</th> <th width="25%">Other Boilerplates</th> <th width="25%">nodejs-fs โญ</th> </tr> <tr> <td> โŒ Hours of setup โŒ Security gaps โŒ No auth included โŒ Basic structure โŒ No best practices </td> <td> โš ๏ธ Minimal setup โŒ No database โŒ No authentication โŒ Outdated patterns โš ๏ธ Basic only </td> <td> โš ๏ธ Overengineered โš ๏ธ Too opinionated โŒ Steep learning curve โš ๏ธ Hard to modify โš ๏ธ Limited docs </td> <td> โœ… 60-second setup โœ… Production-ready โœ… Full auth system โœ… Modern patterns โœ… Well documented โœ… Easy to customize โœ… Actively maintained </td> </tr> </table> --- ## ๐Ÿ“ What's Included