A comprehensive, production-ready backend API built with Node.js, Express.js, MongoDB, Redis, and Socket.IO. This backend provides authentication, user management, real-time messaging, notifications, activity tracking, subscription management, and more.
- Authentication & Authorization - JWT-based auth with role-based access control
- User Management - Complete user CRUD operations with profile management
- Real-time Messaging - Socket.IO powered chat system
- Push Notifications - Firebase Cloud Messaging integration
- Activity Tracking - Comprehensive user activity logging
- Online Status Tracking - Real-time user presence system
- Subscription Management - Stripe integration for payments
- File Upload - Multi-format file upload with validation
- Blog System - Content management system
- Email System - Transactional emails with templates
- Redis Caching - High-performance caching layer
- Rate Limiting - API protection with Nginx
- Real-time Updates - WebSocket connections for live data
- Comprehensive Logging - Winston-based logging system
- Data Validation - Zod schema validation
- Error Handling - Centralized error management
- Health Checks - Application monitoring endpoints
- Docker Support - Complete containerization
- Database Indexing - Optimized MongoDB queries
- Runtime: Node.js 20+
- Framework: Express.js
- Database: MongoDB with Mongoose ODM
- Cache: Redis
- Real-time: Socket.IO
- Authentication: JWT
- Validation: Zod
- File Upload: Multer
- Email: Nodemailer
- Payments: Stripe
- Push Notifications: Firebase Admin SDK
- Logging: Winston
- Process Manager: PM2 (production)
- Containerization: Docker & Docker Compose
- Reverse Proxy: Nginx
- Node.js 20+ and npm/pnpm
- MongoDB 7.0+
- Redis 7.0+
- Docker & Docker Compose (optional)
-
Clone the repository
git clone <repository-url> cd backend-template-db
-
Environment Setup
cp .env.example .env # Edit .env with your configuration -
Start with Docker Compose
docker-compose up -d
-
Access the application
- API: http://localhost:5000
- MongoDB: localhost:27017
- Redis: localhost:6379
-
Install dependencies
pnpm install
-
Start MongoDB and Redis
# MongoDB mongod --dbpath /path/to/data # Redis redis-server
-
Environment Setup
cp .env.example .env # Configure your environment variables -
Start development server
pnpm run dev
src/
├── app/
│ ├── errors/ # Error handling
│ ├── middlewares/ # Express middlewares
│ └── modules/ # Feature modules
│ ├── auth/ # Authentication
│ ├── user/ # User management
│ ├── blog/ # Blog system
│ ├── message/ # Messaging
│ ├── notification/ # Notifications
│ ├── activityLog/ # Activity tracking
│ ├── onlineStatus/ # Online presence
│ └── subscription/ # Payment subscriptions
├── config/ # Configuration files
├── helpers/ # Utility functions
├── jobs/ # Cron jobs
├── shared/ # Shared utilities
├── socket/ # Socket.IO handlers
├── types/ # TypeScript types
└── routes/ # Route definitions
Create a .env file with the following variables:
# Server
NODE_ENV=development
PORT=5000
IP_ADDRESS=localhost
# Database
DATABASE_URL=mongodb://localhost:27017/backend-template-db
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_URL=redis://localhost:6379
# JWT
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRE_IN=7d
JWT_REFRESH_SECRET=your-refresh-secret-key
JWT_REFRESH_EXPIRES_IN=30d
# Email
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=[email protected]
EMAIL_PASS=your-app-password
EMAIL_FROM=[email protected]
# Firebase (Push Notifications)
FIREBASE_PROJECT_ID=your-project-id
FIREBASE_PRIVATE_KEY_ID=your-private-key-id
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=[email protected]
FIREBASE_CLIENT_ID=your-client-id
# Stripe (Payments)
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
# File Upload
UPLOAD_FOLDER=./uploads
MAX_FILE_SIZE=5242880
ALLOWED_FILE_TYPES=image/jpeg,image/jpg,image/png,image/webpPOST /api/v1/auth/sign-in- User loginPOST /api/v1/auth/verify-email- Email verificationPOST /api/v1/auth/forgot-password- Password reset requestPOST /api/v1/auth/reset-password- Reset passwordPOST /api/v1/auth/change-password- Change passwordPOST /api/v1/auth/refresh-token- Refresh access token
POST /api/v1/user/sign-up- User registrationGET /api/v1/user/me- Get current userPATCH /api/v1/user/profile-update- Update profileGET /api/v1/user/all- Get all users (Admin)DELETE /api/v1/user/account- Delete account
GET /api/v1/online-status/online-users- Get online usersPOST /api/v1/online-status/heartbeat- Update user activityGET /api/v1/notifications/my-notifications- Get notificationsPOST /api/v1/notifications/device-token/register- Register push token
GET /api/v1/activity-logs/my-activities- Get user activitiesGET /api/v1/activity-logs/all- Get all activities (Admin)GET /api/v1/activity-logs/stats- Activity statistics
GET /api/v1/messages/messages- Get messagesPOST /api/v1/messages/message-with-image- Send message with image
POST /api/v1/blog/create-blog- Create blog post (Admin)GET /api/v1/blog/all-blogs- Get all blog postsGET /api/v1/blog/blog-details/:id- Get blog postPATCH /api/v1/blog/update-blog/:id- Update blog post (Admin)DELETE /api/v1/blog/delete-blog/:id- Delete blog post (Admin)
GET /api/v1/subscriptions/plans- Get subscription plansPOST /api/v1/subscriptions/create- Create subscriptionGET /api/v1/subscriptions/status- Get subscription statusPOST /api/v1/subscriptions/cancel- Cancel subscription
Client to Server:
register- Register user for real-time updatessendMessage- Send a messageactiveChat- Set active chat sessionmarkAsRead- Mark messages as readtyping- User typing indicatorheartbeat- Keep user online
Server to Client:
receiver-{userId}- Receive new messagemessage-sent- Message delivery confirmationuser:online- User came onlineuser:offline- User went offlinenotification:{userId}- New notificationonlineUsers- Updated online users list
GET /- Basic health checkGET /health- Detailed health status
- Development: Console output with colors
- Production: File-based logging with rotation
- Levels: Error, Warn, Info, Debug
- Storage:
logs/directory with daily rotation
All user actions are automatically logged including:
- Authentication events
- Profile updates
- Content creation/modification
- File uploads
- Admin actions
- JWT Authentication with refresh tokens
- Rate Limiting via Nginx
- Input Validation with Zod schemas
- SQL Injection Protection via Mongoose
- XSS Protection with helmet middleware
- CORS Configuration for cross-origin requests
- File Upload Validation with type/size limits
- Password Hashing with bcrypt
- Role-based Access Control
-
Production Build
docker-compose -f docker-compose.prod.yml up -d
-
Environment Configuration
# Update .env for production NODE_ENV=production DATABASE_URL=mongodb://your-production-db REDIS_URL=redis://your-production-redis
-
Build Application
pnpm run build
-
Start Production Server
pnpm start
-
Process Management (PM2)
pm2 start ecosystem.config.js
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Run linting
pnpm lint
# Fix linting issues
pnpm lint:fix- Redis Caching for frequently accessed data
- Database Indexing for optimized queries
- Connection Pooling for database connections
- Gzip Compression via Nginx
- Static File Caching with proper headers
- Query Optimization with aggregation pipelines
- Memory Management with proper cleanup jobs
Automated cleanup jobs run periodically:
- Activity Logs: Cleaned every day (90-day retention)
- Notifications: Expired notifications removed daily
- Offline Users: Updated every 5 minutes
- File Cleanup: Unused files removed weekly
# MongoDB maintenance
db.runCommand({compact: "collection_name"})
# Redis maintenance
redis-cli FLUSHDB- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Run linting and tests
- Submit a pull request
This project is licensed under the ISC License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the API documentation
- Review the logs for debugging
- Initial release with core features
- Authentication and user management
- Real-time messaging and notifications
- Activity tracking and online status
- Subscription management
- Docker support
- Comprehensive API documentation