{"id":29475373,"url":"https://github.com/ahmadalsharef994/multi-tenant-saas-api","last_synced_at":"2025-07-14T16:08:29.061Z","repository":{"id":138441566,"uuid":"565156098","full_name":"ahmadalsharef994/multi-tenant-saas-api","owner":"ahmadalsharef994","description":"🏢 Enterprise-grade multi-tenant SaaS API built with Node.js, Express, and MongoDB featuring tenant isolation, role-based access control, and scalable architecture","archived":false,"fork":false,"pushed_at":"2025-07-10T14:22:18.000Z","size":29,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-07-10T21:06:27.355Z","etag":null,"topics":["architecture","database","example","mongodb","multitenancy","nodejs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ahmadalsharef994.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-11-12T14:14:06.000Z","updated_at":"2025-07-10T14:22:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"1bc053da-538d-4957-a39d-3ba4d069455f","html_url":"https://github.com/ahmadalsharef994/multi-tenant-saas-api","commit_stats":null,"previous_names":["ahmadalsharef994/multi-tenant-saas-api"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ahmadalsharef994/multi-tenant-saas-api","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmadalsharef994%2Fmulti-tenant-saas-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmadalsharef994%2Fmulti-tenant-saas-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmadalsharef994%2Fmulti-tenant-saas-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmadalsharef994%2Fmulti-tenant-saas-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ahmadalsharef994","download_url":"https://codeload.github.com/ahmadalsharef994/multi-tenant-saas-api/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahmadalsharef994%2Fmulti-tenant-saas-api/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265314822,"owners_count":23745355,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["architecture","database","example","mongodb","multitenancy","nodejs"],"created_at":"2025-07-14T16:08:28.372Z","updated_at":"2025-07-14T16:08:29.046Z","avatar_url":"https://github.com/ahmadalsharef994.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🏢 Multi-Tenant SaaS API\n\nA production-ready multi-tenant Software-as-a-Service (SaaS) API built with Node.js, Express.js, and MongoDB. Designed for enterprise applications requiring complete tenant isolation, role-based access control, and scalable architecture.\n\n## ✨ Features\n\n### 🔐 Multi-Tenancy Architecture\n- **Complete Tenant Isolation**: Each tenant's data is completely separated\n- **Database Per Tenant**: Dedicated MongoDB database for each tenant\n- **Tenant-Aware Routing**: Automatic tenant identification and routing\n- **Cross-Tenant Security**: Prevents data leakage between tenants\n\n### 🛡️ Security \u0026 Authentication\n- **JWT Authentication**: Secure token-based authentication\n- **Role-Based Access Control (RBAC)**: Granular permission management\n- **Tenant-Scoped Permissions**: Roles and permissions isolated per tenant\n- **Password Hashing**: Secure password storage with bcrypt\n\n### 🚀 Enterprise Features\n- **RESTful API Design**: Clean, standardized API endpoints\n- **Middleware Architecture**: Modular and extensible middleware system\n- **Error Handling**: Comprehensive error handling and logging\n- **Request Validation**: Input validation and sanitization\n- **Rate Limiting**: Protection against abuse and DoS attacks\n\n### 📊 Scalability \u0026 Performance\n- **Connection Pooling**: Efficient database connection management\n- **Caching Layer**: Redis integration for improved performance\n- **Horizontal Scaling**: Designed for multi-instance deployment\n- **Database Indexing**: Optimized queries and performance\n\n## 🛠️ Tech Stack\n\n- **Backend**: Node.js, Express.js\n- **Database**: MongoDB with Mongoose ODM\n- **Authentication**: JWT (JSON Web Tokens)\n- **Security**: bcrypt, helmet, cors\n- **Validation**: Joi or express-validator\n- **Environment**: dotenv for configuration\n\n## 📋 Prerequisites\n\n- Node.js 16+ and npm\n- MongoDB 4.4+\n- Redis (optional, for caching)\n\n## 🚀 Installation\n\n1. **Clone the repository:**\n```bash\ngit clone https://github.com/ahmadalsharef994/multi-tenant-saas-api.git\ncd multi-tenant-saas-api\n```\n\n2. **Install dependencies:**\n```bash\nnpm install\n```\n\n3. **Configure environment variables:**\n```bash\ncp .env.example .env\n# Edit .env with your configuration\n```\n\n4. **Start the application:**\n```bash\n# Development mode\nnpm run dev\n\n# Production mode\nnpm start\n```\n\n## ⚙️ Configuration\n\n### Environment Variables\n```env\n# Server Configuration\nPORT=3000\nNODE_ENV=development\n\n# Database Configuration\nMONGODB_URI=mongodb://localhost:27017/\nDB_NAME_PREFIX=tenant_\n\n# JWT Configuration\nJWT_SECRET=your_jwt_secret_here\nJWT_EXPIRES_IN=24h\n\n# Redis Configuration (optional)\nREDIS_URL=redis://localhost:6379\n```\n\n### Tenant Configuration\n```javascript\n// Example tenant structure\n{\n  \"tenantId\": \"company-abc\",\n  \"name\": \"Company ABC\",\n  \"domain\": \"company-abc.yourapp.com\",\n  \"dbName\": \"tenant_company_abc\",\n  \"settings\": {\n    \"maxUsers\": 100,\n    \"features\": [\"analytics\", \"reports\"]\n  }\n}\n```\n\n## 🎯 API Endpoints\n\n### Authentication\n```bash\nPOST /api/auth/login          # Tenant user login\nPOST /api/auth/register       # Tenant user registration\nPOST /api/auth/refresh        # Refresh JWT token\nPOST /api/auth/logout         # User logout\n```\n\n### Tenant Management\n```bash\nGET    /api/tenants           # List all tenants (admin only)\nPOST   /api/tenants           # Create new tenant\nGET    /api/tenants/:id       # Get tenant details\nPUT    /api/tenants/:id       # Update tenant\nDELETE /api/tenants/:id       # Delete tenant\n```\n\n### User Management (Tenant-Scoped)\n```bash\nGET    /api/users             # List tenant users\nPOST   /api/users             # Create user\nGET    /api/users/:id         # Get user details\nPUT    /api/users/:id         # Update user\nDELETE /api/users/:id         # Delete user\n```\n\n### Roles \u0026 Permissions\n```bash\nGET    /api/roles             # List tenant roles\nPOST   /api/roles             # Create role\nPUT    /api/roles/:id         # Update role\nDELETE /api/roles/:id         # Delete role\n```\n\n## 🏗️ Architecture\n\n### Multi-Tenant Strategy\n```\n┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐\n│   Tenant A      │    │   Tenant B      │    │   Tenant C      │\n│   Database      │    │   Database      │    │   Database      │\n└─────────────────┘    └─────────────────┘    └─────────────────┘\n         │                       │                       │\n         └───────────────────────┼───────────────────────┘\n                                 │\n                    ┌─────────────────┐\n                    │  Application    │\n                    │  Layer          │\n                    └─────────────────┘\n```\n\n### Request Flow\n1. **Tenant Identification**: Extract tenant from subdomain/header\n2. **Database Selection**: Connect to tenant-specific database\n3. **Authentication**: Verify JWT token and tenant access\n4. **Authorization**: Check role-based permissions\n5. **Business Logic**: Execute tenant-scoped operations\n6. **Response**: Return tenant-specific data\n\n## 📚 Usage Examples\n\n### Creating a New Tenant\n```javascript\nconst response = await fetch('/api/tenants', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'Authorization': 'Bearer ' + adminToken\n  },\n  body: JSON.stringify({\n    name: 'Acme Corporation',\n    domain: 'acme.yourapp.com',\n    adminEmail: 'admin@acme.com'\n  })\n});\n```\n\n### Tenant-Scoped User Authentication\n```javascript\nconst response = await fetch('/api/auth/login', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    'X-Tenant-ID': 'acme-corp'\n  },\n  body: JSON.stringify({\n    email: 'user@acme.com',\n    password: 'securepassword'\n  })\n});\n```\n\n## 🔧 Development\n\n### Running Tests\n```bash\nnpm test                    # Run all tests\nnpm run test:watch         # Run tests in watch mode\nnpm run test:coverage      # Generate coverage report\n```\n\n### Code Quality\n```bash\nnpm run lint              # Run ESLint\nnpm run format            # Format code with Prettier\n```\n\n### Database Migration\n```bash\nnpm run migrate           # Run database migrations\nnpm run seed              # Seed test data\n```\n\n## 🚀 Deployment\n\n### Docker Deployment\n```dockerfile\n# Dockerfile included for containerized deployment\ndocker build -t multi-tenant-api .\ndocker run -p 3000:3000 multi-tenant-api\n```\n\n### Production Considerations\n- Use process managers (PM2, Docker)\n- Configure reverse proxy (Nginx)\n- Set up monitoring and logging\n- Implement backup strategies\n- Use environment-specific configurations\n\n## 🔒 Security Best Practices\n\n- **Input Validation**: All inputs validated and sanitized\n- **SQL Injection Prevention**: Parameterized queries with Mongoose\n- **XSS Protection**: Content Security Policy headers\n- **Rate Limiting**: Prevent abuse and DoS attacks\n- **HTTPS Only**: Force secure connections in production\n- **Tenant Isolation**: Complete data separation between tenants\n\n## 📈 Performance Optimization\n\n- **Database Indexing**: Optimized queries with proper indexes\n- **Connection Pooling**: Efficient database connection management\n- **Caching**: Redis integration for frequently accessed data\n- **Compression**: Gzip compression for API responses\n- **CDN Integration**: Static asset delivery optimization\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## 📜 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 📞 Support\n\nFor support and questions:\n- 🐛 Issues: [GitHub Issues](https://github.com/ahmadalsharef994/multi-tenant-saas-api/issues)\n\n\n---\n\n**Built for enterprise-grade multi-tenant applications** 🏢\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmadalsharef994%2Fmulti-tenant-saas-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahmadalsharef994%2Fmulti-tenant-saas-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahmadalsharef994%2Fmulti-tenant-saas-api/lists"}