This is the server-side of a real-time chat application with file-sharing capabilities. Built using Node.js, Express, Socket.IO, and MongoDB, it allows users to join chat rooms, send/receive real-time messages, and share files using Node.js streams and buffers. User authentication, chat history, and file metadata are stored securely in MongoDB.
Frontend Client: For the complete chat application experience, you'll also need the frontend client. Check out the Chat Frontend Repository which provides:
- Modern Next.js React interface
- Real-time UI updates
- Responsive design
- Optimized performance
- Socket.IO client integration
- Real-time Communication: Users can send and receive messages in real-time using Socket.IO
- Message Reactions: React to messages with emojis, real-time reaction updates
- Message Editing/Deletion: Edit sent messages and soft delete with permissions
- Message Threads/Replies: Reply to specific messages and create threaded conversations
- Mentions: @mention functionality with real-time notifications
- Message Status: Sent, delivered, and read status indicators
- Typing Indicators: Real-time "user is typing" notifications
- Message Search: Full-text search within chat history with pagination
- Pinned Messages: Pin important messages to chat rooms
- Starred Messages: Personal message bookmarking system
- File Sharing: Efficient file uploads/downloads with Node.js streams and buffers
- File Metadata: Store and retrieve file information with messages
- User Authentication: Secure JWT-based login and registration
- Permission System: Role-based access control for message operations
- Input Validation: Comprehensive Joi-based validation
- Rate Limiting: Configurable rate limits for different endpoints
- Persistent Storage: MongoDB with optimized schemas and indexing
- Real-time Updates: Socket.IO events for all messaging features
- Scalability: Horizontal scaling support with concurrent user optimization
- Comprehensive Testing: 80%+ coverage with unit, integration, and performance tests
- Node.js: JavaScript runtime for building server-side logic
- Express: Fast web framework for Node.js with RESTful API design
- Socket.IO: Real-time, bidirectional communication with comprehensive event handling
- MongoDB: NoSQL database with optimized schemas for chat features
- Mongoose: ODM for MongoDB with advanced querying and population
- JWT: Secure user authentication using JSON Web Tokens
- Joi: Schema validation for all API endpoints
- Bcrypt: Password hashing and security
- Multer: File upload handling with stream processing
- Jest: Comprehensive testing framework
.
├── .env.example
├── .gitignore
├── LICENSE
├── package.json
├── README.md
├── API.md
├── CHANGELOG.md
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
├── SECURITY.md
├── swagger.js
├── seeder.js
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ ├── feature_request.md
│ │ └── question.md
│ └── PULL_REQUEST_TEMPLATE.md
├── src/
│ ├── app.js
│ ├── config/
│ │ ├── database.js
│ │ ├── environment.js
│ │ ├── jwtConfig.js
│ │ └── socket.js
│ ├── controllers/
│ │ ├── authController.js
│ │ ├── chatController.js
│ │ ├── chatRoomController.js
│ │ └── fileController.js
│ ├── middleware/
│ │ ├── authMiddleware.js
│ │ ├── errorHandler.js
│ │ └── rateLimiter.js
│ ├── models/
│ │ ├── ChatRoom.js
│ │ ├── File.js
│ │ ├── Message.js
│ │ └── User.js
│ ├── routes/
│ │ ├── authRoutes.js
│ │ ├── chatRoomRoutes.js
│ │ └── chatRoutes.js
│ ├── services/
│ │ ├── authService.js
│ │ ├── chatService.js
│ │ ├── fileService.js
│ │ ├── messageService.js
│ │ └── socketService.js
│ ├── utils/
│ │ ├── fileUpload.js
│ │ ├── logger.js
│ │ └── responseFormatter.js
│ └── validations/
│ ├── auth.js
│ ├── chatRoom.js
│ ├── file.js
│ └── message.js
├── tests/
│ ├── auth.test.js
│ ├── chat.test.js
│ ├── chatRoom.test.js
│ ├── fileUpload.test.js
│ ├── integration.test.js
│ ├── message.test.js
│ └── performance.test.js
├── uploads/
└── views/
├── layouts/
└── *.ejs- Node.js (version 14 or above)
- MongoDB (locally or cloud-hosted)
- Docker (optional, for containerized deployment)
-
Clone the repository:
git clone https://github.com/jmrashed/chat-backend.git cd chat-backend -
Install dependencies:
npm install
-
Create a
.envfile:In the root of the project directory, create a
.envfile with the following content:PORT=3000 MONGODB_URI=mongodb://localhost:27017/realtime-chat-app JWT_SECRET=your_secret_key
-
Start MongoDB:
Make sure MongoDB is running locally or connect to your cloud MongoDB instance.
mongod
-
Run the server:
Start the application with:
npm start
-
Access the Application:
Open your browser and navigate to
http://localhost:3000.
Comprehensive test suite covering unit, integration, and performance tests:
# Run all tests
npm test
# Run specific test suites
npm run test:unit # Unit tests (auth, chat rooms, messages, files)
npm run test:integration # Integration tests (full API flows)
npm run test:performance # Performance tests (load testing)
npm run test:coverage # Generate coverage report
npm run test:watch # Watch mode for developmentTo run the server in a Docker container:
-
Build the Docker image:
docker build -t realtime-chat-app-server . -
Run the Docker container:
docker run -d -p 3000:3000 realtime-chat-app-server
-
Access the Application:
Navigate to
http://localhost:3000to use the chat application.
For API documentation, you can explore the endpoints through Postman or Swagger:
- Postman Documentation: Postman Collection
- Swagger UI: Available locally at
/api-docsafter starting the server.
- Horizontal Scaling: Cluster the app or use multiple instances behind a load balancer.
- Redis: Use Redis to handle session management and WebSocket scaling with Socket.IO.
- Database Indexing: Ensure MongoDB collections are indexed for optimal query performance.
- Rate Limiting: Implement rate limiting to control API usage and prevent server overload.
Robust error handling throughout the application:
- Invalid JWT tokens and authentication failures
- Database connection and query errors
- File upload/download issues and validation
- Input validation with detailed error messages
- Consistent error response format
- Unit Tests: Individual component testing (auth, rooms, messages, files)
- Integration Tests: Full API workflow testing
- Performance Tests: Load testing and concurrent user simulation
- Coverage: 80%+ test coverage with detailed reports
- Rate limiting on all endpoints (configurable per endpoint type)
- Input validation and sanitization
- File type and size restrictions
- Environment-specific CORS configuration
- Secure password hashing with bcrypt
- JSDoc documentation for all functions
- Consistent error handling patterns
- Environment-specific configurations
- Clean, maintainable code structure
POST /api/chat/messages- Send message with optional reply/mentionsGET /api/chat/messages/:room- Get messages with paginationPUT /api/chat/messages/:id- Edit message (owner only)DELETE /api/chat/messages/:id- Soft delete message (owner only)GET /api/chat/messages/search- Search messages with filters
POST /api/chat/messages/:id/react- Add emoji reactionDELETE /api/chat/messages/:id/react/:reactionId- Remove reaction
PUT /api/chat/messages/:id/read- Mark message as readPUT /api/chat/messages/:id/pin- Pin/unpin message
POST /api/chat/favorites- Add message to favoritesDELETE /api/chat/favorites/:messageId- Remove from favoritesGET /api/chat/favorites- Get user's favorite messages
sendMessage,receiveMessage,receiveReplyaddReaction,removeReaction,reactionAdded,reactionRemovededitMessage,deleteMessage,messageEdited,messageDeletedmarkAsRead,messageRead,messageDeliveredtypingStart,typingStop,userTyping,userStoppedTypingpinMessage,messagePinned,messageUnpinnedmention- Real-time mention notifications
- Push Notifications: Mobile and web push notifications for mentions
- Voice Messages: Audio message recording and playback
- Message Encryption: End-to-end encryption for sensitive conversations
- Advanced Search: Search by date range, file type, user, etc.
- Message Templates: Quick reply templates and saved responses
- Admin Dashboard: Comprehensive admin panel for user and content management
This project is licensed under the MIT License.
Here are some screenshots of the project:
Md Rasheduzzaman
Full-Stack Software Engineer & Technical Project Manager
Building scalable, secure & AI-powered SaaS platforms across ERP, HRMS, CRM, LMS, and E-commerce domains.
Over 10 years of experience leading full-stack teams, cloud infrastructure, and enterprise-grade software delivery.
🌐 Portfolio: jmrashed.github.io
✉️ Email: jmrashed@gmail.com
💼 LinkedIn: linkedin.com/in/jmrashed
📝 Blog: medium.com/@jmrashed
💻 GitHub: github.com/jmrashed
"Need a Reliable Software Partner? I build scalable, secure & modern solutions for startups and enterprises."
