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:
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.
- Create a file named
server.js:
touch server.js
- 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.
- Create a directory named
publicand navigate into it:
mkdir public cd public
- Create an
index.htmlfile:
touch index.html
- 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
- Start your server:
node server.js
- 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!