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

codeTap to expand ⛶
1// Chat Client — WebSocket Integration
2
3class ChatClient {
4 constructor(url) {
5 this.url = url;
6 this.ws = null;
7 this.listeners = {};
8 this.reconnectAttempts = 0;
9 this.maxReconnects = 5;
10 }
11
12 connect(username) {
13 this.username = username;
14 this.ws = new WebSocket(this.url);
15
16 this.ws.onopen = () => {
17 console.log("Connected!");
18 this.reconnectAttempts = 0;
19 this.send("join", { username });
20 this.emit("connected");
21 };
22
23 this.ws.onmessage = (event) => {
24 const { type, payload } = JSON.parse(event.data);
25 this.emit(type, payload);
26 };
27
28 this.ws.onclose = () => {
29 this.emit("disconnected");
30 this.tryReconnect();
31 };
32
33 this.ws.onerror = (error) => {
34 console.error("WebSocket error:", error);
35 };
36 }
37
38 send(type, payload) {
39 if (this.ws?.readyState === WebSocket.OPEN) {
40 this.ws.send(JSON.stringify({ type, payload }));
41 }
42 }
43
44 sendMessage(text, room = "general") {
45 this.send("message", {
46 text,
47 room,
48 sender: this.username,
49 timestamp: new Date().toISOString()
50 });
51 }
52
53 sendTyping(room) {
54 this.send("typing", { user: this.username, room });
55 }
56
57 // Event system
58 on(event, callback) {
59 (this.listeners[event] ||= []).push(callback);
60 }
61
62 emit(event, data) {
63 this.listeners[event]?.forEach(cb => cb(data));
64 }
65
66 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 }
72
73 disconnect() {
74 this.ws?.close();
75 }
76}
77
78// Usage
79const chat = new ChatClient("wss://chat.example.com");
80
81// Listen for events
82chat.on("message", ({ sender, text, timestamp }) => {
83 appendMessage(sender, text, timestamp);
84});
85
86chat.on("typing", ({ user }) => {
87 showTypingIndicator(user);
88});
89
90chat.on("userList", ({ users }) => {
91 updateOnlineUsers(users);
92});
93
94// Connect and send
95chat.connect("Alice");
96
97// Send message on form submit
98document.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});
106
107// Typing indicator (debounced)
108const debouncedTyping = debounce(() => chat.sendTyping("general"), 500);
109document.querySelector("#messageInput").addEventListener("input", debouncedTyping);

🏋️ Practice Exercise

Build It Yourself:

  1. Set up a Node.js WebSocket server with the ws library
  2. Create the chat UI with message list, input, and online users
  3. Implement real-time message sending/receiving
  4. Add typing indicators (debounced)
  5. Implement chat rooms/channels
  6. Add reconnection logic with exponential backoff
  7. 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 closed

  • Not 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.