Project 4: Real-Time Chat App
📖 Concept
Build a real-time chat application using WebSockets. This project practices WebSocket communication, real-time data handling, event-driven architecture, and state synchronization.
Features:
- Real-time messaging between users
- Typing indicators
- Online/offline status
- Message timestamps
- Chat rooms/channels
- Message history
Tech: Browser's WebSocket API + Node.js ws library (or Socket.io) Concepts practiced: WebSockets, Events, JSON, DOM, async patterns, State management
💻 Code Example
1// Chat Client — WebSocket Integration23class ChatClient {4 constructor(url) {5 this.url = url;6 this.ws = null;7 this.listeners = {};8 this.reconnectAttempts = 0;9 this.maxReconnects = 5;10 }1112 connect(username) {13 this.username = username;14 this.ws = new WebSocket(this.url);1516 this.ws.onopen = () => {17 console.log("Connected!");18 this.reconnectAttempts = 0;19 this.send("join", { username });20 this.emit("connected");21 };2223 this.ws.onmessage = (event) => {24 const { type, payload } = JSON.parse(event.data);25 this.emit(type, payload);26 };2728 this.ws.onclose = () => {29 this.emit("disconnected");30 this.tryReconnect();31 };3233 this.ws.onerror = (error) => {34 console.error("WebSocket error:", error);35 };36 }3738 send(type, payload) {39 if (this.ws?.readyState === WebSocket.OPEN) {40 this.ws.send(JSON.stringify({ type, payload }));41 }42 }4344 sendMessage(text, room = "general") {45 this.send("message", {46 text,47 room,48 sender: this.username,49 timestamp: new Date().toISOString()50 });51 }5253 sendTyping(room) {54 this.send("typing", { user: this.username, room });55 }5657 // Event system58 on(event, callback) {59 (this.listeners[event] ||= []).push(callback);60 }6162 emit(event, data) {63 this.listeners[event]?.forEach(cb => cb(data));64 }6566 tryReconnect() {67 if (this.reconnectAttempts >= this.maxReconnects) return;68 this.reconnectAttempts++;69 const delay = Math.min(1000 * 2 ** this.reconnectAttempts, 30000);70 setTimeout(() => this.connect(this.username), delay);71 }7273 disconnect() {74 this.ws?.close();75 }76}7778// Usage79const chat = new ChatClient("wss://chat.example.com");8081// Listen for events82chat.on("message", ({ sender, text, timestamp }) => {83 appendMessage(sender, text, timestamp);84});8586chat.on("typing", ({ user }) => {87 showTypingIndicator(user);88});8990chat.on("userList", ({ users }) => {91 updateOnlineUsers(users);92});9394// Connect and send95chat.connect("Alice");9697// Send message on form submit98document.querySelector("#chatForm").addEventListener("submit", (e) => {99 e.preventDefault();100 const input = document.querySelector("#messageInput");101 if (input.value.trim()) {102 chat.sendMessage(input.value.trim());103 input.value = "";104 }105});106107// Typing indicator (debounced)108const debouncedTyping = debounce(() => chat.sendTyping("general"), 500);109document.querySelector("#messageInput").addEventListener("input", debouncedTyping);
🏋️ Practice Exercise
Build It Yourself:
- Set up a Node.js WebSocket server with the
wslibrary - Create the chat UI with message list, input, and online users
- Implement real-time message sending/receiving
- Add typing indicators (debounced)
- Implement chat rooms/channels
- Add reconnection logic with exponential backoff
- Bonus: Add emoji support, file sharing, and message reactions
⚠️ Common Mistakes
Not handling WebSocket disconnections — always implement reconnection logic
Sending messages without checking
readyState— causes errors if connection is closedNot debouncing typing indicators — floods the server with typing events
Not sanitizing messages before rendering — XSS vulnerability through chat messages
Storing all chat history in memory — paginate and load history from server
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Project 4: Real-Time Chat App. Login to unlock this feature.