Skip to content

Latest commit

Β 

History

48 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Real-Time Chat Application

A modern, scalable real-time chat application built with React (TypeScript) and Node.js, featuring Socket.io for real-time communication. This application uses in-memory storage for simplicity and can be easily extended with database integration.

✨ Features

  • Real-time messaging with Socket.io
  • Multiple chat rooms support
  • Typing indicators to show when users are composing messages
  • Online users list with real-time updates
  • Message history for each room (last 100 messages)
  • Responsive design that works on desktop and mobile
  • Modern UI with TailwindCSS
  • TypeScript for better development experience
  • In-memory storage (no database required)

πŸ› οΈ Tech Stack

Backend

  • Node.js - JavaScript runtime
  • Express.js - Web framework
  • Socket.io - Real-time communication
  • CORS - Cross-origin resource sharing
  • UUID - Unique identifier generation

Frontend

  • React 18 - UI library
  • TypeScript - Static type checking
  • Vite - Build tool and development server
  • TailwindCSS - Utility-first CSS framework
  • Socket.io-client - Real-time client communication

πŸ“ Project Structure

Real-Time-Chat/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ package.json
β”‚   └── server.js              # Express + Socket.io server
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ public/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ Login.tsx      # User authentication & room selection
β”‚   β”‚   β”‚   β”œβ”€β”€ ChatRoom.tsx   # Main chat interface
β”‚   β”‚   β”‚   β”œβ”€β”€ MessageList.tsx    # Message display with grouping
β”‚   β”‚   β”‚   β”œβ”€β”€ MessageInput.tsx   # Message composition
β”‚   β”‚   β”‚   β”œβ”€β”€ TypingIndicator.tsx # Typing status display
β”‚   β”‚   β”‚   └── OnlineUsers.tsx    # Online users sidebar
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   └── socketService.ts   # Socket.io client wrapper
β”‚   β”‚   β”œβ”€β”€ App.tsx            # Main application component
β”‚   β”‚   β”œβ”€β”€ main.tsx          # Application entry point
β”‚   β”‚   └── index.css         # Global styles with TailwindCSS
β”‚   β”œβ”€β”€ package.json
β”‚   β”œβ”€β”€ vite.config.ts
β”‚   β”œβ”€β”€ tailwind.config.js
β”‚   └── tsconfig.json
β”œβ”€β”€ README.md
└── LICENSE

πŸš€ Quick Start

Prerequisites

  • Node.js (v16 or higher)
  • npm or yarn

Installation & Setup

  1. Clone the repository

    git clone <repository-url>
    cd Real-Time-Chat
  2. Setup Backend

    cd backend
    npm install
    npm start

    The backend server will start on http://localhost:3001

  3. Setup Frontend (in a new terminal)

    cd frontend
    npm install
    npm run dev

    The frontend will start on http://localhost:5173

  4. Open your browser

    Navigate to http://localhost:5173 and start chatting!

Development Mode

For development with auto-reload:

Backend:

cd backend
npm run dev  # Uses nodemon for auto-restart

Frontend:

cd frontend
npm run dev  # Vite dev server with hot reload

πŸ”§ Configuration

Backend Configuration

The server can be configured through environment variables:

PORT=3001                    # Server port (default: 3001)

Frontend Configuration

Update the Socket.io server URL in src/services/socketService.ts:

constructor(serverUrl: string = 'http://localhost:3001') {
  this.serverUrl = serverUrl;
}

πŸ“‘ API & Socket Events

Socket.io Events

Client β†’ Server

Event Payload Description
joinRoom { username: string, room: string } Join a chat room
leaveRoom {} Leave current room
sendMessage { message: string } Send a message
typing { isTyping: boolean } Toggle typing indicator

Server β†’ Client

Event Payload Description
message Message New message received
roomHistory Message[] Chat history when joining
onlineUsers User[] Updated online users list
typing { users: User[] } Users currently typing
leftRoom {} Confirmation of leaving room
error { message: string } Error messages

Data Structures

interface User {
  id: string;
  username: string;
  room: string;
  socketId: string;
}

interface Message {
  id: string;
  username: string;
  message: string;
  timestamp: string;
  type: 'user' | 'system';
}

REST Endpoints

Method Endpoint Description
GET /health Server health check with statistics

🎨 UI Components

Login Component

  • Username validation (2-20 characters, alphanumeric + spaces)
  • Room name input with suggestions
  • Form validation with error handling
  • Loading states during connection

ChatRoom Component

  • Header with room name and user info
  • Message list with auto-scroll
  • Real-time typing indicators
  • Online users sidebar (desktop) / modal (mobile)
  • Responsive design for all screen sizes

MessageList Component

  • Message grouping for better readability
  • Timestamp display
  • User/system message differentiation
  • Auto-scroll to new messages
  • Empty state handling

MessageInput Component

  • Auto-resizing textarea
  • Send on Enter, new line on Shift+Enter
  • Typing indicator with debouncing
  • Character counter for long messages
  • Disabled state handling

πŸ”’ Data Storage & Memory Management

In-Memory Storage Structure

const storage = {
  users: new Map(),        // userId β†’ User object
  rooms: new Map(),        // roomName β†’ { users: Set(), messages: [] }
  sockets: new Map(),      // socketId β†’ userId
  typingUsers: new Map()   // roomName β†’ Set(userIds)
};

Memory Optimization

  • Message Limit: Only the last 100 messages per room are stored
  • Automatic Cleanup: Users are removed from storage on disconnect
  • Typing Timeout: Typing indicators auto-clear after 2 seconds
  • Connection Management: Proper cleanup on socket disconnection

πŸ“± Responsive Design

The application is fully responsive with:

  • Mobile-first approach using TailwindCSS
  • Adaptive layouts for different screen sizes
  • Touch-friendly interfaces for mobile devices
  • Collapsible sidebar on smaller screens
  • Optimized message bubbles for readability

πŸš€ Future Improvements

Authentication & Security

  • JWT-based authentication
  • User registration and profiles
  • Private messaging
  • Message encryption
  • Rate limiting and spam protection

Database Integration

  • MongoDB/PostgreSQL for persistent storage
  • Message history pagination
  • User preferences and settings
  • File upload and sharing
  • Message search functionality

Scalability

  • Redis for session management
  • Horizontal scaling with multiple server instances
  • Load balancing
  • CDN integration for assets
  • Caching strategies

Enhanced Features

  • Voice and video calling
  • Screen sharing
  • Rich text formatting
  • Emoji reactions
  • Message threads and replies
  • Push notifications
  • Dark mode theme
  • Multiple language support

DevOps & Deployment

  • Docker containerization
  • CI/CD pipeline
  • Environment-specific configs
  • Monitoring and logging
  • Health checks and alerts

πŸ› Troubleshooting

Common Issues

  1. Connection refused

    • Ensure backend server is running on port 3001
    • Check firewall settings
    • Verify CORS configuration
  2. Messages not appearing

    • Check browser console for JavaScript errors
    • Verify Socket.io connection status
    • Ensure proper event handling
  3. Styling issues

    • Verify TailwindCSS is properly configured
    • Check for conflicting CSS rules
    • Ensure proper class names are used

Development Tips

  • Use browser developer tools to monitor Socket.io events
  • Check server logs for connection and error messages
  • Test with multiple browser tabs to simulate multiple users
  • Use React Developer Tools for component debugging

οΏ½β€πŸ’» Developer

Developed by: Danuja Adikari
Email: danujadikari2001@gmail.com
GitHub: @danujaadikari

οΏ½πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ž Support

If you encounter any issues or have questions:

  1. Check the troubleshooting section above
  2. Search existing issues in the repository
  3. Create a new issue with detailed information
  4. Include error messages and reproduction steps

Happy Chatting! πŸŽ‰

About

πŸ’¬ Real-Time Chat Application – A modern React + Node.js chat app with Socket.io, supporting multiple rooms, typing indicators, online users list, and responsive design.

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages