Written by: ekwoster.dev on Fri Aug 01

Building a Real-Time Chat App with Node.js and Socket.io

Building a Real-Time Chat App with Node.js and Socket.io

Cover image for Building a Real-Time Chat App with Node.js and Socket.io

Building a Real-Time Chat App with Node.js and Socket.io

Real-time communication is at the heart of many modern web applications, from customer support widgets to full-blown instant messaging apps. In this blog post, we’ll walk through the process of building a simple real-time chat application using Node.js and Socket.io. We’ll cover the foundational concepts, show you how to set up the project, and provide a clear code example to help you get started.

Why Use Node.js and Socket.io?

Node.js is a powerful JavaScript runtime built on Chrome’s V8 engine. It excels at handling asynchronous operations and real-time data communication. Socket.io is a JavaScript library that enables real-time, bi-directional communication between clients and servers, making it a natural fit for chat applications.

Together, these two tools are perfect for creating apps that require low-latency communication between users in an efficient and scalable manner.

What We’ll Build

We’ll build a basic chat application that allows multiple users to connect, choose a username, and send real-time messages visible to all connected participants.

Prerequisites

Before you begin, make sure you have the following installed:

  • Node.js (v14 or later)
  • npm (Node package manager)
  • Basic knowledge of JavaScript and HTML

Step 1: Initialize the Project

Let’s start by setting up the project structure.

mkdir node-chat-app
cd node-chat-app
npm init -y

Install the required dependencies:

npm install express socket.io

Step 2: Set Up the Server

Create a file named server.js in your root directory:

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.use(express.static('public'));

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

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });

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

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

Step 3: Create the Frontend

Create a public folder and add an index.html file.

<!DOCTYPE html>
<html>
<head>
  <title>Chat App</title>
  <style>
    body { font-family: Arial, sans-serif; }
    #messages { list-style: none; padding: 0; }
    #messages li { padding: 5px 10px; }
    #form { display: flex; }
    #input { flex: 1; padding: 10px; }
  </style>
</head>
<body>
  <ul id="messages"></ul>
  <form id="form">
    <input id="input" autocomplete="off" /><button>Send</button>
  </form>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();

    const form = document.getElementById('form');
    const input = document.getElementById('input');
    const messages = document.getElementById('messages');

    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });

    socket.on('chat message', function(msg) {
      const item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  </script>
</body>
</html>

Step 4: Run the Application

Start the server by running:

node server.js

Navigate to http://localhost:3000 in your browser. Open it in multiple tabs or browsers to simulate a multi-user chat environment. When you send a message from one client, it should appear on all connected clients in real-time.

How It Works

Let’s break down what’s happening:

  • The server listens for incoming Socket.io connections.
  • When a client emits a ‘chat message’ event, the server broadcasts it to all connected clients.
  • Each client receives new messages and displays them in real-time without requiring a page reload.

Enhancing the App

This is a basic chat application, but there’s so much more you can add:

  • Usernames: Let users pick a username when they join.
  • Rooms: Create chat rooms and let users join specific rooms.
  • Typing indicators: Show when a user is typing.
  • Storing Messages: Use a database like MongoDB to persist messages.
  • Authentication: Add user account management.

Best Practices for Real-World Usage

  • Scale using a message broker like Redis when deploying across multiple servers.
  • Use namespaces or rooms for managing large groups of clients.
  • Secure your connections with HTTPS and use authentication.

Conclusion

Building a real-time chat app with Node.js and Socket.io is not only fun but also a powerful way to learn about web sockets and real-time communication. While we've only scratched the surface, this example lays the foundation for more complex applications that rely on instant updates and interactivity.

Give it a try and start experimenting—you’ll be amazed at how powerful real-time web apps can be!

💡 If you need this done – we offer such services: https://ekwoster.dev/service/fullstack-development