A modern, scalable real-time chat application backend built with Node.js, Express.js, Socket.io, and MongoDB. Features include instant messaging, user presence tracking, room management, and comprehensive API endpoints for building chat applications.
- Real-time Messaging: Instant messaging with Socket.io WebSockets
- Multiple Chat Rooms: Create and join public/private chat rooms
- Private Messaging: Direct messaging between users
- User Presence: Online/offline status tracking and typing indicators
- Message Management: Edit, delete, pin messages with reactions
- Room Administration: Admin controls and member management
- User Authentication: Secure JWT-based authentication
- Message Search: Full-text search across conversations
- File Sharing: Framework ready for file and media sharing
- Node.js (v18+) - JavaScript runtime for server-side development
- ES6+ Modules - Modern JavaScript with import/export syntax
- Express.js - Fast, unopinionated web framework for Node.js
- Socket.io - Real-time bidirectional event-based communication
- Mongoose - MongoDB object modeling for Node.js
- JWT (jsonwebtoken) - Secure token-based authentication
- bcryptjs - Password hashing and encryption
- MongoDB - NoSQL document database
- MongoDB Atlas - Cloud-hosted MongoDB service
- Helmet - Security headers and protection
- CORS - Cross-Origin Resource Sharing configuration
- Express Rate Limit - API rate limiting and abuse prevention
- Express Validator - Request validation and sanitization
Traditional relational databases struggle with chat applications due to their rigid schema requirements. Our chat application benefits from MongoDB's flexible document structure:
// Messages can have different types and metadata
{
_id: ObjectId,
content: "Hello world!",
type: "text", // Can be 'text', 'image', 'file'
sender: ObjectId,
room: ObjectId,
reactions: [ // Dynamic array of reactions
{ user: ObjectId, emoji: "π", createdAt: Date },
{ user: ObjectId, emoji: "β€οΈ", createdAt: Date }
],
metadata: { // Flexible metadata for different message types
fileUrl: "https://...", // Only for file messages
fileName: "document.pdf",
fileSize: 1024000
}
}- Horizontal Scaling: MongoDB easily scales across multiple servers
- Embedded Documents: Store related data together for faster reads
- Flexible Indexing: Create indexes on any field for optimized queries
- Real-time Aggregation: Perfect for chat statistics and analytics
Chat applications evolve rapidly with new features:
- Add new message types without schema migrations
- Introduce new user preferences dynamically
- Extend room settings without database downtime
- Support different room types with varying properties
- API Responses: Direct JSON output without ORM conversion overhead
- Real-time Data: Socket.io naturally works with JSON objects
- Frontend Integration: Seamless data flow to React/Vue/Angular applications
- Node.js (v18.0.0 or higher)
- MongoDB Atlas Account (free tier available) or local MongoDB installation
- npm or yarn package manager
- Git for version control
git clone https://github.com/farhapartex/chat-app-backend
cd chat-app-backend# Using yarn (recommended)
yarn install# Copy environment template
cp .env.example .env
# Edit .env file with your configuration
nano .envRequired Environment Variables:
# Server Configuration
PORT=5000
NODE_ENV=development
# Database (MongoDB Atlas recommended)
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/chatapp?retryWrites=true&w=majority
# JWT Authentication
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRES_IN=7d
# CORS Configuration
CORS_ORIGIN=http://localhost:3000- Visit MongoDB Atlas
- Click "Try Free" and create your account
- Create a new cluster (select M0 Sandbox - FREE)
- Choose AWS provider and region closest to you
- Database Access: Create a database user with read/write permissions
- Network Access: Add your IP address (or 0.0.0.0/0 for development)
- Connect: Get your connection string and add it to
.env
# With hot reload
yarn devyarn start# Test server health
curl http://localhost:5000/health
# Expected response:
{
"status": "OK",
"message": "Chat API is running",
"database": "connected",
"uptime": 5.2
}curl -X POST http://localhost:3000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "password123",
"bio": "Test user account"
}'curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "password123"
}'curl -X POST http://localhost:3000/api/rooms \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"name": "General Discussion",
"description": "Welcome to our general chat room!",
"type": "public",
"category": "general"
}'chat-app-backend/
βββ src/
β βββ config/
β β βββ database.js # MongoDB connection configuration
β β βββ socket.js # Socket.io real-time event handlers
β βββ controllers/
β β βββ authController.js # Authentication HTTP endpoints
β β βββ messageController.js # Message management endpoints
β β βββ roomController.js # Room management endpoints
β βββ middleware/
β β βββ auth.js # JWT authentication middleware
β β βββ errorHandler.js # Global error handling
β βββ models/
β β βββ User.js # User schema and methods
β β βββ Room.js # Chat room schema and methods
β β βββ Message.js # Message schema and methods
β βββ routes/
β β βββ auth.js # Authentication routes
β β βββ messages.js # Message routes
β β βββ rooms.js # Room routes
β βββ services/
β β βββ authService.js # Authentication business logic
β β βββ messageService.js # Message business logic
β β βββ roomService.js # Room business logic
β βββ utils/
β β βββ constants.js # Application constants
β βββ app.js # Express application setup
βββ server.js # Server entry point
βββ package.json # Dependencies and scripts
βββ .env.example # Environment variables template
βββ README.md # Project documentation
{
"scripts": {
"start": "node server.js", # Production server
"dev": "nodemon server.js", # Development with hot reload
"test": "jest", # Run tests (when implemented)
"lint": "eslint src/", # Code linting
"format": "prettier --write src/" # Code formatting
}
}The application provides comprehensive REST API endpoints:
- Authentication (
/api/auth/*) - User registration, login, profile management - Rooms (
/api/rooms/*) - Chat room creation, management, discovery - Messages (
/api/messages/*) - Message operations, search, history
For complete API documentation, start the server and visit the interactive endpoints or check the controller files.
- JWT Authentication with secure token generation and validation
- Password Hashing using bcrypt with salt rounds
- Rate Limiting to prevent API abuse and spam
- Input Validation with comprehensive sanitization
- CORS Protection with configurable origins
- Security Headers via Helmet middleware
- MongoDB Injection protection through Mongoose
Built with β€οΈ using modern Node.js and NoSQL technologies