Building a Real-Time Chat Application with Node.js

In the realm of modern web development, real-time communication has become a standard feature, and creating a real-time chat application is an excellent way to delve into this exciting realm. In this article, we will guide you through the process of building a real-time chat application using Node.js, Express, and Socket.io.

Prerequisites

Before we dive into the code, ensure you have Node.js and npm (Node Package Manager) installed on your machine. You can download them from Node.js official website.

Setting Up the Project

  1. Create a new project directory:

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

Initialize the project:

npm init -y

Install necessary packages:

npm install express socket.io

Setting Up the Server

Create a file named server.js and set up the basic Express server with Socket.io integration.

// server.js
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

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

Creating the Frontend

Create an index.html file:

<!-- 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 App</title>
</head>
<body>
  <h1>Welcome to the Real-Time Chat App</h1>
</body>
</html>

Update the server to serve static files:

// Add this line to server.js
app.use(express.static('public'));

Create a public directory and add a style.css file:

/* public/style.css */
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f4f4f4;
}

h1 {
  text-align: center;
}

Link the CSS file in index.html:

<!-- Add this line to index.html -->
<link rel="stylesheet" href="/style.css">

Implementing Real-Time Chat with Socket.io

Update index.html for chat functionality:

<!-- Add these lines to index.html -->
<input type="text" id="username" placeholder="Enter your username">
<input type="text" id="messageInput" placeholder="Type your message...">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>

<script src="/socket.io/socket.io.js"></script>
<script src="/client.js"></script>

Create a client.js file in the public directory:

// public/client.js
const socket = io();

function sendMessage() {
  const username = document.getElementById('username').value;
  const message = document.getElementById('messageInput').value;

  if (username && message) {
    socket.emit('chatMessage', { username, message });
    document.getElementById('messageInput').value = '';
  }
}

socket.on('chatMessage', (data) => {
  const messages = document.getElementById('messages');
  const li = document.createElement('li');
  li.innerText = `${data.username}: ${data.message}`;
  messages.appendChild(li);
});

Update the server to handle chat messages:

// Update the connection event in server.js
io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });

  socket.on('chatMessage', (data) => {
    io.emit('chatMessage', data);
  });
});

Running the Application

Start the server:

node server.js

Visit http://localhost:3000/ in your browser.

Open multiple tabs or browsers to simulate different users and start chatting in real-time.

Congratulations! You’ve successfully built a real-time chat application using Node.js, Express, and Socket.io. Feel free to enhance the application by adding features like user authentication, private messaging, or message timestamps. This project provides a solid foundation for exploring more advanced real-time applications.