A production-ready, security-focused real-time chat application built with the MERN stack, implementing industry-standard security practices and modern web technologies.
- JWT (JSON Web Tokens) for stateless authentication
- Secure token generation and validation
- HTTP-only cookies to prevent XSS attacks
- Token expiration and refresh mechanisms
- Protected API endpoints with middleware authentication
-
Password Security
- Bcrypt hashing algorithm for password encryption
- Salting with configurable rounds for enhanced security
- No plain-text password storage
-
Message Encryption
- Messages encrypted using bcrypt before storage
- Secure transmission over encrypted channels
- Protection against data breach exposure
-
Client-Side Validation
- Real-time input validation on login and signup forms
- Format verification (email, password strength)
- Prevention of malformed data submission
-
Server-Side Validation
- Comprehensive input sanitization
- SQL injection prevention
- XSS (Cross-Site Scripting) attack mitigation
- Data type and format verification
-
Private Routing
- Protected routes requiring authentication
- Automatic redirection for unauthorized access
- Route guards preventing URL manipulation
-
Role-Based Access Control
- User session management
- Authorization checks on sensitive operations
- Secure API endpoint protection
-
Socket.io Security
- Secure WebSocket connections
- Origin validation
- Connection authentication
- Protection against socket hijacking
-
CORS Configuration
- Restricted cross-origin requests
- Whitelisted domains only
- Secure headers implementation
- Frontend: React.js with Hooks
- Backend: Node.js + Express.js
- Database: MongoDB with Mongoose ODM
- Real-time: Socket.io
- Styling: TailwindCSS + DaisyUI
- bcryptjs: Password hashing and encryption
- jsonwebtoken: JWT authentication
- cookie-parser: Secure cookie handling
- express-validator: Input validation middleware
- Zustand: Lightweight global state management
- React Context: Real-time user status management
Create a .env file in the root directory with the following variables:
# Server Configuration
PORT=5000
NODE_ENV=production
# Database
MONGO_DB_URI=<your mongodbcluster uri>
# Security
JWT_SECRET=your_super_secure_random_string_min_32_chars
- JWT_SECRET: Use a cryptographically strong random string (minimum 32 characters)
- MONGO_DB_URI: Never commit to version control; use environment-specific values
- NODE_ENV: Set to 'production' for deployment to enable security optimizations
- Node.js (v14 or higher)
- MongoDB Atlas account or local MongoDB installation
- npm or yarn package manager
-
Clone the repository
git clone https://github.com/yashpatil118/SecureChat.git cd SecureChat -
Install dependencies
npm install
-
Configure environment variables
cp .env.example .env # Edit .env with your secure credentials -
Build the application
npm run build
-
Start the application
# Production mode npm start # Development mode npm run dev
- Real-time Messaging: Instant message delivery using Socket.io
- User Authentication: Secure signup and login system
- Online Status: Real-time user presence indicators
- Message History: Persistent chat storage with MongoDB
- User Profiles: Customizable user information
- Private Conversations: One-on-one messaging
- Session Management: Secure user sessions with automatic timeout
- HTTPS Ready: Configured for SSL/TLS encryption
- Rate Limiting: Protection against brute-force attacks
- Error Handling: Secure error messages without information leakage
- Audit Logging: Track authentication events and suspicious activities
message-app/
β
βββ backend/
β βββ controllers/
β β βββ auth.controller.js # Authentication logic (signup, login, logout)
β β βββ message.controller.js # Message handling with encryption
β β βββ user.controller.js # User management & retrieval
β β
β βββ db/
β β βββ connectToMongoDB.js # Secure MongoDB connection
β β
β βββ middleware/
β β βββ protectRoute.js # JWT validation & route protection
β β
β βββ models/
β β βββ conversation.model.js # Conversation schema
β β βββ message.model.js # Message schema with encryption
β β βββ user.model.js # User schema with password hashing
β β
β βββ routes/
β β βββ auth.routes.js # Authentication endpoints
β β βββ message.routes.js # Protected message routes
β β βββ user.routes.js # Protected user routes
β β
β βββ socket/
β β βββ socket.js # Secure Socket.io configuration
β β
β βββ utils/
β β βββ generateToken.js # JWT token generation utility
β β
β βββ server.js # Express server setup
β
βββ frontend/
β βββ public/
β β βββ bg.png # Background image
β β βββ vite.svg # Vite logo
β β
β βββ src/
β βββ assets/
β β βββ sounds/
β β βββ notification.mp3 # Message notification sound
β β
β βββ components/
β β βββ messages/
β β β βββ Message.jsx # Individual message component
β β β βββ MessageContainer.jsx
β β β βββ MessageInput.jsx # Input with validation
β β β βββ Messages.jsx # Message list display
β β β
β β βββ sidebar/
β β β βββ Conversation.jsx # Conversation item
β β β βββ Conversations.jsx # Conversations list
β β β βββ LogoutButton.jsx # Secure logout
β β β βββ SearchInput.jsx # Search with validation
β β β βββ Sidebar.jsx # Main sidebar
β β β
β β βββ skeletons/
β β βββ MessageSkeleton.jsx # Loading state
β β
β βββ context/
β β βββ AuthContext.jsx # Authentication state management
β β βββ SocketContext.jsx # Socket.io connection context
β β
β βββ hooks/
β β βββ useGetConversations.js # Fetch conversations
β β βββ useGetMessage.js # Fetch messages
β β βββ useListenMessages.js # Real-time message listener
β β βββ useLogin.js # Login with validation
β β βββ useLogout.js # Secure logout
β β βββ useSendMessage.js # Send message with validation
β β βββ useSignup.js # Signup with validation
β β
β βββ pages/
β β βββ home/
β β β βββ Home.jsx # Protected home page
β β βββ login/
β β β βββ Login.jsx # Login page with validation
β β βββ signup/
β β βββ GenderCheckbox.jsx # Gender selection
β β βββ SignUp.jsx # Signup with validation
β β
β βββ utils/
β β βββ emojis.js # Emoji utilities
β β βββ extractTime.js # Time formatting
β β
β βββ zustand/
β β βββ useConversation.js # Global state management
β β
β βββ App.jsx # Main app with routing
β βββ main.jsx # App entry point
β βββ index.css # Global styles
β
βββ .env # Environment variables (ignored)
βββ .gitignore # Git ignore file
βββ package.json # Project dependencies
protectRoute.js: JWT middleware for authenticationgenerateToken.js: Secure token generation with expiryuser.model.js: Password hashing with bcrypt pre-save hooksauth.controller.js: Input validation & authentication logic
AuthContext.jsx: Protected authentication stateuseLogin.js/useSignup.js: Client-side validation hooks- All
pages/: Private routing implementation
-
Password Policy
- Minimum 6 characters length
- Complexity requirements enforced
- Bcrypt encryption
-
JWT Security
- Short-lived access tokens
- HTTP-only cookie storage
- Secure flag in production
- Token validation on every request
-
Input Validation
- Whitelist approach for allowed characters
- Length restrictions on all inputs
- Email format validation
- Prevention of NoSQL injection
-
Error Handling
- Generic error messages to users
- Detailed logs for administrators
- No stack traces in production
- Proper status codes
-
Database Security
- Connection string encryption
- Prepared statements (Mongoose queries)
- Limited user permissions
- Regular backup procedures
- Form validation with user-friendly messages
- Network error handling with retry mechanisms
- Graceful degradation for failed features
- Toast notifications for user feedback
- Comprehensive try-catch blocks
- Async error handling middleware
- Database connection error management
- Socket.io error listeners
- Set
NODE_ENV=production - Use strong JWT_SECRET
- Enable HTTPS/SSL
- Configure CORS properly
- Set secure cookie flags
- Enable rate limiting
- Configure MongoDB security
- Set up monitoring and alerts
- Regular security audits
- Dependency vulnerability scanning
- Backend: Heroku, DigitalOcean, AWS EC2
- Database: MongoDB Atlas (with IP whitelist)
- Frontend: Vercel, Netlify
When contributing, please ensure:
- All security tests pass
- No sensitive data in commits
- Follow secure coding guidelines
- Update security documentation
MIT License - See LICENSE file for details
Note: This application implements security best practices, but no system is 100% secure. Regular security audits, dependency updates, and monitoring are essential for maintaining a secure application.