A robust, scalable Node.js backend API for the Echo social media platform, providing real-time chat, video calling, post management, and user authentication features. Built with Express.js, MongoDB, Socket.io, and Redis for optimal performance.
- Production:
https://api.echo.linkpc.net - Frontend: Echo App
- Repository: Echo-Backend
- JWT-based Authentication with access & refresh tokens
- Password Encryption using bcrypt
- Email Verification system
- Password Reset functionality
- Rate Limiting for API protection
- CORS Configuration for secure cross-origin requests
- Cookie-based Session Management
- Socket.io Integration for instant messaging
- Message Encryption/Decryption for privacy
- Real-time Notifications for new messages
- Group Conversations support
- Online/Offline Status tracking
- Message Read Receipts
- File/Media Sharing capabilities
- WebRTC Signaling Server for peer-to-peer connections
- Call Management (initiate, accept, decline, end)
- Audio/Video Call Support
- Call Notifications and status updates
- ICE Candidate Exchange for connectivity
- Post Creation & Management with media upload
- Like/Unlike functionality
- Comment System with threaded replies
- User Following/Followers system
- Feed Generation based on connections
- User Search with advanced filtering
- Profile Management with customizable information
- MongoDB with Mongoose ODM
- Redis for session storage and caching
- Cloudinary for media storage and optimization
- MeiliSearch for advanced search capabilities
- Node-Cache for in-memory caching
- Node.js - Runtime environment
- Express.js 4.21.1 - Web framework
- MongoDB 8.8.3 - NoSQL database
- Mongoose - MongoDB object modeling
- Socket.io 4.8.1 - Real-time communication
- Redis 4.7.0 - In-memory data store
- JWT - Authentication tokens
- Helmet 8.0.0 - Security headers
- CORS 2.8.5 - Cross-origin resource sharing
- Express Rate Limit 7.4.1 - Request rate limiting
- Express Validator 7.2.0 - Input validation
- Cookie Parser 1.4.7 - Cookie handling
- Multer 1.4.5 - File upload middleware
- Cloudinary 2.5.1 - Cloud media storage
- Node-Cache 5.1.2 - Memory caching
- Nodemailer 6.9.16 - Email service
- MeiliSearch 0.50.0 - Full-text search engine
- BCrypt 5.1.1 - Password hashing
Backend/
βββ index.js # Main server entry point
βββ package.json # Dependencies and scripts
βββ .env # Environment variables
βββ controllers/ # Business logic controllers
β βββ AdminController/ # Admin operations
β β βββ uploadAll.js # Bulk data upload
β βββ AuthControllers/ # Authentication logic
β β βββ userLogin.js # User login
β β βββ userRegister.js # User registration
β β βββ userLogout.js # User logout
β β βββ verifyUser.js # Email verification
β β βββ forgetPassword.js # Password reset request
β β βββ verifyResetToken.js # Reset token validation
β β βββ updatePassword.js # Password update
β β βββ loggedPassword.js # Logged-in password change
β βββ ChatControllers/ # Chat functionality
β β βββ chatList.js # Get user conversations
β β βββ fetchChats.js # Fetch chat messages
β βββ PostControllers/ # Post management
β β βββ uploadPost.js # Create new post
β β βββ feedPost.js # Get user feed
β β βββ fetchPosts.js # Fetch user posts
β β βββ fetchComments.js # Get post comments
β β βββ likePost.js # Like/unlike posts
β β βββ postComment.js # Add comments
β β βββ deletePost.js # Delete posts
β βββ UserControllers/ # User management
β βββ userProfile.js # Get user profile
β βββ userAbout.js # Get user details
β βββ userBasic.js # Basic user info
β βββ updateProfile.js # Update profile
β βββ searchUser.js # Search users
β βββ followUser.js # Follow users
β βββ unfollowUser.js # Unfollow users
β βββ fetchFollowers.js # Get followers
β βββ fetchFollowing.js # Get following
β βββ removeFollower.js # Remove follower
β βββ checkExistingUser.js # Check user existence
β βββ deleteAccount.js # Delete user account
βββ models/ # Database schemas
β βββ user.js # User model
β βββ post.js # Post model
β βββ comment.js # Comment model
β βββ conversation.js # Conversation model
β βββ message.js # Message model
βββ routes/ # API route definitions
β βββ authRoutes.js # Authentication routes
β βββ userRoutes.js # User management routes
β βββ postRoutes.js # Post-related routes
β βββ chatRoutes.js # Chat functionality routes
β βββ adminRoute.js # Admin operations routes
βββ middlewares/ # Custom middleware
β βββ cookieAuthentication.js # JWT auth middleware
β βββ limiter.js # Rate limiting middleware
βββ sockets/ # Socket.io event handlers
β βββ onConnection.js # Main socket connection handler
β βββ events/ # Individual socket events
β βββ online.js # User online status
β βββ offline.js # User offline status
β βββ sendMessage.js # Send chat messages
β βββ readMsg.js # Mark messages as read
β βββ joinAllRooms.js # Join chat rooms
β βββ callUser.js # Initiate calls
β βββ callAccepted.js # Accept calls
β βββ declinedCall.js # Decline calls
β βββ cancelCall.js # Cancel calls
β βββ endCall.js # End calls
β βββ sendOffer.js # WebRTC offer
β βββ sendAnswer.js # WebRTC answer
β βββ sendNewOffer.js # New WebRTC offer
β βββ sendNewAnswer.js # New WebRTC answer
β βββ sendIceCandidate.js # ICE candidates
β βββ newPost.js # New post notifications
β βββ deletePost.js # Post deletion events
β βββ offlineMessages.js # Handle offline messages
β βββ removeOfflineMessages.js # Remove offline messages
β βββ redirectConvo.js # Redirect conversations
β βββ leaveChat.js # Leave chat rooms
βββ Utils/ # Utility functions
β βββ mongoConnect.js # MongoDB connection
β βββ redis.js # Redis configuration
β βββ cloudinary.js # Cloudinary setup
β βββ mail.js # Email service
β βββ cookie.js # JWT token utilities
β βββ cache.js # Caching utilities
β βββ io.js # Socket.io setup
β βββ sockets.js # Socket configuration
β βββ encryptdecryptMsg.js # Message encryption
β βββ getRoomId.js # Chat room ID generation
β βββ meilisearchConnect.js # Search engine setup
βββ public/ # Static files
βββ temp/ # Temporary file storage
βββ templates/ # Email templates
βββ verifyEmail.html # Email verification template
βββ forgetPassword.html # Password reset template
{
email: String (unique, required),
isVerified: Boolean (default: false),
profileStatus: Boolean (default: false),
password: String (hashed),
username: String (unique, lowercase),
fullname: String,
dob: String,
gender: String,
bio: String,
website: String,
interests: String,
follower: [ObjectId] (ref: 'user'),
following: [ObjectId] (ref: 'user'),
profileImage: String (default URL),
coverImage: String (default URL),
timestamps: true
}{
userId: ObjectId (ref: 'user', required),
caption: String,
media: String (required),
ratio: String (required),
likes: [ObjectId] (ref: 'user'),
comments: [ObjectId] (ref: 'comment'),
timestamps: true
}{
participants: [ObjectId] (ref: 'user', required),
roomId: String,
messages: [ObjectId] (ref: 'message'),
timestamps: true
}{
sender: ObjectId (ref: 'user', required),
receiver: ObjectId (ref: 'user', required),
conversationId: ObjectId (ref: 'conversation', required),
message: String (encrypted, required),
iv: String (encryption vector),
read: Boolean (default: false),
timestamps: true
}{
userId: ObjectId (ref: 'user', required),
postId: ObjectId (ref: 'post', required),
comment: String (required),
timestamps: true
}POST /create # Register new user
POST /verify # Verify email
POST /login # User login
POST /logout # User logout
POST /forget-password # Request password reset
GET /verify-reset-token/:token # Verify reset token
POST /update-password/:token # Update password with token
POST /update/logged/password # Update password (logged in)
GET /profile/:username # Get user profile
GET /about # Get current user details
GET /basic/:username # Get basic user info
PUT /update # Update user profile
GET /search/:query # Search users
POST /follow # Follow user
POST /unfollow # Unfollow user
GET /followers/:username # Get user followers
GET /following/:username # Get user following
POST /remove/follower # Remove follower
GET /check/:username # Check if user exists
DELETE /delete # Delete user account
POST /upload # Create new post
GET /feed # Get user feed
GET /user/:username # Get user posts
GET /comments/:postId # Get post comments
POST /like # Like/unlike post
POST /comment # Add comment to post
DELETE /:postId # Delete post
GET /list/:userId # Get user conversations
GET /fetch/msg/:conversationId # Fetch chat messages
POST /upload/all # Bulk upload data
// User Status
"online"; // User comes online
"offline"; // User goes offline
// Chat Events
"joinAllRooms"; // Join multiple chat rooms
"sendMessage"; // Send chat message
"receiveMsg"; // Receive chat message
"readMsg"; // Mark message as read
"offlineMessage"; // Handle offline messages
"rmOfflineMsg"; // Remove offline messages
"redirectConvo"; // Redirect to conversation
// Calling Events
"callUser"; // Initiate call
"receiveCall"; // Receive incoming call
"acceptedCall"; // Accept call
"callAccepted"; // Call accepted notification
"declinedCall"; // Decline call
"cancelledCall"; // Call cancelled
"CancelCall"; // Cancel ongoing call
"endCall"; // End call
// WebRTC Signaling
"sendOffer"; // Send WebRTC offer
"getOffer"; // Receive WebRTC offer
"sendAnswer"; // Send WebRTC answer
"getAnswer"; // Receive WebRTC answer
"sendNewOffer"; // Send new offer (renegotiation)
"sendNewAnswer"; // Send new answer (renegotiation)
"sendIceCandidate"; // Send ICE candidate
"getIceCandidate"; // Receive ICE candidate
// Post Events
"newPost"; // New post notification
"deletePost"; // Post deletion notification- Node.js 16+
- MongoDB
- Redis
- Cloudinary account
- MeiliSearch (optional)
-
Clone the repository
git clone https://github.com/akashkhedar/Echo-Backend.git cd Echo-Backend -
Install dependencies
npm install
-
Environment Variables Create a
.envfile with the following variables:PORT=5000 NODE_ENV=development # Database MONGODB_URI=mongodb://localhost:27017/echo # Redis REDIS_URL=redis://localhost:6379 # JWT Secrets JWT_ACCESS_SECRET=your_access_secret JWT_REFRESH_SECRET=your_refresh_secret # Cloudinary CLOUDINARY_CLOUD_NAME=your_cloud_name CLOUDINARY_API_KEY=your_api_key CLOUDINARY_API_SECRET=your_api_secret # Email Service EMAIL_HOST=smtp.gmail.com EMAIL_PORT=587 EMAIL_USER=[email protected] EMAIL_PASS=your_app_password # MeiliSearch MEILISEARCH_HOST=http://localhost:7700 MEILISEARCH_API_KEY=your_meilisearch_key
-
Start the server
npm start
# Start with nodemon for development
npx nodemon index.jsconst allowedOrigins = [
"http://localhost:3000", // Development frontend
"https://app.echo.linkpc.net", // Production frontend
];- Access Token: 1 hour expiry, HTTP-only
- Refresh Token: 7 days expiry, HTTP-only
- Secure: True in production
- SameSite: "None" in production, "Lax" in development
- Auth Routes: Limited to prevent brute force attacks
- General API: Standard rate limiting applied
- Password Hashing: BCrypt with salt rounds
- JWT Tokens: Separate access and refresh tokens
- Token Rotation: Automatic token refresh
- Session Management: Redis-based session storage
- Message Encryption: End-to-end message encryption
- Input Validation: Express-validator for all inputs
- SQL Injection: MongoDB's natural protection
- XSS Protection: Helmet security headers
- Rate Limiting: Prevents API abuse
- CORS: Controlled cross-origin access
- Cookie Security: HTTP-only, secure cookies
- Environment Variables: Sensitive data protection
- Node-Cache: In-memory caching for frequently accessed data
- Redis: Session storage and distributed caching
- MongoDB Indexing: Optimized database queries
- Cloudinary: Optimized media storage and delivery
- Multer: Efficient file upload handling
- Temporary Storage: Automatic cleanup of temp files
- Connection Pooling: MongoDB connection management
- Index Strategy: Optimized queries with proper indexing
- Population: Efficient data fetching with Mongoose
- Use Postman collection for comprehensive API testing
- Authentication flow testing
- Socket.io event testing
- File upload testing
- WebRTC signaling performance
- Concurrent user handling
- Database query optimization
-
Environment Configuration
NODE_ENV=production
-
Database Setup
- MongoDB Atlas or self-hosted MongoDB
- Redis Cloud or self-hosted Redis
-
Media Storage
- Cloudinary for image/video storage
- CDN configuration for optimal delivery
-
SSL Certificate
- HTTPS required for WebRTC
- Secure cookie configuration
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["npm", "start"]- Error logging and tracking
- Performance metrics
- Socket connection monitoring
- Database query performance
- Database connectivity
- Redis connection status
- External service availability
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow REST API conventions
- Implement proper error handling
- Add input validation for all endpoints
- Write comprehensive tests
- Document new features
This project is licensed under the MIT License. See the LICENSE file for details.
- Echo Frontend - React.js web application
- Echo Mobile - React Native mobile app
For support, email [email protected] or create an issue on GitHub.
- Express.js - Fast, unopinionated web framework
- Socket.io - Real-time communication
- MongoDB - Flexible NoSQL database
- Cloudinary - Media management platform
- Redis - In-memory data structure store
Built with β€οΈ by Akash Khedar
Echo Backend - Powering real-time social connections