Codeground AI
EditorWorkspacesInterviews Meet New Daily Challenges
Data & format
  • JSON DiffCompare two JSON blobs side by side
  • Diff & PatchGenerate unified patches from text/code
  • JSON FormatterPretty-print and validate JSON
  • SQL FormatterFormat SQL and explain with AI
  • JSON ↔ CSVConvert tabular data both ways
  • Base64 CodecEncode and decode Base64
  • Log ParserPretty-print logs and highlight severity
Security & web
  • JWT DebuggerDecode and verify JSON Web Tokens
  • ENV LinterLint .env files and redact values
  • Password GeneratorStrong, configurable passwords
  • UUID GeneratorGenerate UUID v1/v4 in bulk
  • Regex TesterTest patterns in real time
Generators & utilities
  • Epoch ConverterConvert between Unix and dates
  • Meeting PlannerMatrix of slots across timezones
  • Date MathAdd duration with timezone awareness
  • Cron BuilderValidate cron and preview next runs
  • QR GeneratorMake scannable QR codes
  • Color PickerPick & convert colors
  • Lucky Draw WheelSpin-the-wheel utility
Network & creative
  • Speed TestMeasure network throughput
  • Diagram StudioFlowcharts & architecture diagrams
  • Canvas DrawingA scratchpad for sketches
  • Turtle GameCoding game for kids
See everything Codeground AI offers
Reads
Sign In Sign Up
EditorWorkspacesInterviewsMeetDaily ChallengesReads
Tools
JSON DiffDiff & PatchJSON FormatterSQL FormatterJSON ↔ CSVBase64 CodecLog ParserJWT DebuggerENV LinterPassword GeneratorUUID GeneratorRegex TesterEpoch ConverterMeeting PlannerDate MathCron BuilderQR GeneratorColor PickerLucky Draw WheelSpeed TestDiagram StudioCanvas DrawingTurtle Game

Sign InSign Up

Notifications 0

How to Build a Real-Time Chat Application with Node.js and WebSocket

Shubham Mehta - April 4, 2025


Real-time chat applications are an essential feature of modern web applications, allowing users to communicate instantly. In this tutorial, we will walk you through the process of building a simple real-time chat application using Node.js and WebSocket. By the end of this guide, you will have a functional chat application that you can customize and expand upon.


Prerequisites

Before we start, make sure you have the following installed on your machine:

  1. Node.js (v14 or later)
  2. npm (comes with Node.js)
  3. A text editor (e.g., VS Code)


Step 1: Set Up Your Project

A. Create a new directory for your project:

mkdir real-time-chat
cd real-time-chat

B. Initialize a new Node.js project:

npm init -y

C. Install the necessary packages:

npm install express ws


Step 2: Create the Server

First, we'll set up a simple server using Express and WebSocket.

  1. Create a file named server.js:
touch server.js
  1. Add the following code to server.js:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// Serve the static files
app.use(express.static('public'));

// WebSocket connection
wss.on('connection', (ws) => {
console.log('New client connected');

ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});

ws.on('close', () => {
console.log('Client disconnected');
});
});

// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});


Step 3: Create the Client

Next, we'll create the client-side code to interact with our WebSocket server.

  1. Create a directory named public and navigate into it:
mkdir public
cd public
  1. Create an index.html file:
touch index.html
  1. Add the following code to index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Chat</title>
<style>
body { font-family: Arial, sans-serif; }
#chat { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; }
#message { width: calc(100% - 60px); }
</style>
</head>
<body>
<h1>Real-Time Chat</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type a message...">
<button id="send">Send</button>

<script>
const ws = new WebSocket('ws://localhost:3000');

ws.onmessage = (event) => {
const chat = document.getElementById('chat');
const message = document.createElement('div');
message.textContent = event.data;
chat.appendChild(message);
};

document.getElementById('send').onclick = () => {
const messageInput = document.getElementById('message');
ws.send(messageInput.value);
messageInput.value = '';
};
</script>
</body>
</html>


Step 4: Run the Application

  1. Start your server:
node server.js
  1. Open your browser and navigate to http://localhost:3000.

You should see a simple chat interface where you can type and send messages. Open multiple tabs to test the real-time communication between clients.


Conclusion

Congratulations! You've built a basic real-time chat application using Node.js and WebSocket. This tutorial provides a foundation for creating more advanced chat applications with features like user authentication, message history, and private messaging. Feel free to expand and customize this project to fit your needs.

Stay tuned to our blog for more tutorials and tips on web development!


Codeground AI

The browser is the only IDE you need. Cloud workspaces, 15+ language runtimes, secure interview tooling and a polished developer toolbox — all in one tab.

Languages

  • Node.js
  • Python
  • Java
  • C++
  • Go
  • Rust
  • TypeScript
  • Web (HTML/CSS/JS)
  • Shell / Bash

Databases

  • MongoDB
  • PostgreSQL
  • MySQL
  • Redis
  • ClickHouse

Tools

  • JSON Diff
  • Diff & Patch
  • JSON Formatter
  • JSON ↔ CSV
  • JWT Debugger
  • Base64 Codec
  • Regex Tester
  • Epoch Converter
  • Cron Builder
  • Meeting Planner
  • SQL Formatter
  • ENV Linter
  • Date Math
  • Log Parser
  • QR Generator
  • UUID Generator
  • Color Picker
  • Password Generator
  • Speed Test
  • Diagram Studio
  • Canvas Drawing
  • Lucky Draw Wheel

Platform

  • Daily Challenges
  • Interviews
  • Reads
  • Turtle (Kids)

Company

  • About Us
  • Privacy Policy
  • Sitemap
  • Contact

© 2026 Codeground AI. Built for developers who want to ship.

About·Privacy·Sitemap·[email protected]