Building a Real-Time Chat App with Node.js and Socket.io
Tags: javascript, node, webdev, tutorial
Published: 2023-04-13 08:43:18

## Overview

Chat applications are one of the most popular ways to communicate. If you are interested in building a chat application, you are in the right place. In this tutorial, we will build a real-time chat app using Node.js and [Socket.io](http://socket.io/). We will explain the basic concepts of Node.js and Socket.io and guide you through the process of building this application from scratch.


## Node.js

Node.js is an open-source, cross-platform, server-side JavaScript runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which means that you can use the same language for both the client-side and server-side of your application. Node.js is lightweight and fast, making it an ideal choice for building real-time applications.

## [Socket.io](http://socket.io/)

Socket.io is a JavaScript library that enables real-time, bidirectional, and event-based communication between the client and the server. It is built on top of the WebSockets API and provides a simple and easy-to-use interface for building real-time applications. Socket.io supports multiple transport protocols, including WebSocket, HTTP long-polling, and HTTP streaming, which makes it a reliable and robust solution for real-time communication.

## Step-by-Step Guide

### Step 1: Set up the Node.js environment on your machine.

First, you need to install Node.js on your machine. You can download the latest version of Node.js from the official website. Once you have downloaded and installed Node.js, you can verify the installation by running the following command in your terminal:

```
node -v

```

This command should return the version number of Node.js that you have installed.


### Step 2: Create a new Node.js project and initialize a package.json file using npm.

Now let's create a new Node.js project and initialize a package.json file using npm. A package.json file is a file that contains metadata about your project, such as the name, version, description, dependencies, and scripts.

To create a new Node.js project, run the following command in your terminal:

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

```

The `mkdir` command creates a new directory called `chat-app`, and the `cd` command changes your current working directory to the `chat-app` directory. The `npm init` command initializes a new package.json file with default values. The `-y` flag skips the interactive prompts and uses default values for all fields.

### Step 3: Install the Socket.io library using npm.

Next, you need to install the [Socket.io](http://socket.io/) library using npm (Node Package Manager). npm is a package manager for Node.js that allows you to install and manage third-party packages and libraries.

To install the Socket.io library, run the following command in your terminal:

```
npm install socket.io

```

### Step 4: Create an index.js file and set up the server using the Express framework.

Create an `index.js` file and set up the server using the Express framework. Express is a popular Node.js web framework that provides a simple and easy-to-use interface for building web applications.

To install express framework run the following code:

```
npm install express
```

 Now, open the `index.js` file in your favourite text editor and add the following code:

```
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

```

This code:

- Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 4).
- We define a route handler `/` that gets called when we hit our website home.
- We make the http server listen on port 3000.

### Step 5: Create a client-side HTML file, which will contain the chat interface.

Next, you need to create a client-side HTML file, which will contain the chat interface. 

In Unix and Unix-like operating systems (such as Linux and macOS), run the following command in your terminal:
```
touch index.html

```

In Windows, you can create a new `index.html `file in your terminal by running the following code:
```
New-Item -ItemType File index.html

```

This command creates a new index.html file in your current working directory. Next, open the index.html file in your favourite text editor and add the following code:

```
<!DOCTYPE html>
<html>
  <head>
    <title>Real-Time Chat App</title>
  </head>
  <body>
    <h1>Real-Time Chat App</h1>
    <ul id="messages"></ul>
    <form id="message-form">
      <input type="text" name="message" placeholder="Type your message here...">
      <button>Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
  </body>
</html>

```

This code creates a simple HTML page with a heading, a list of messages, a text input field, and a send button. It also includes the Socket.io client library.


### Step 6: Write the client-side JavaScript code to connect to the server using Socket.io to send and receive messages.


Next, you need to write the client-side JavaScript code to connect to the server using Socket.io. To do this, you need make a `<script> </script>` in the html file and add the following code:

```
const socket = io();

const messageForm = document.getElementById('message-form');
const messageInput = document.querySelector('input[name="message"]');
const messageList = document.getElementById('messages');

messageForm.addEventListener('submit', (e) => {
  e.preventDefault();

  const message = messageInput.value;

  if (message.trim() === '') {
    return;
  }

  socket.emit('message', message);

  messageInput.value = '';
  messageInput.focus();
});

socket.on('message', (message) => {
  const li = document.createElement('li');
  li.textContent = message;
  messageList.appendChild(li);
});

```

This code creates a new Socket.io instance, selects the message form, input field, and message list from the HTML page, and adds event listeners for form submission and incoming messages. When the user submits a message, the code retrieves the message from the input field, emits a `message` event to the server with the message as the payload, clears the input field, and focuses on the input field. When the client receives a `message` event from the server, the code creates a new list item element, sets its text content to the message, and appends it to the message list.


### Step 7: Write the server-side JavaScript code to handle connections, disconnections, and incoming messages.

Finally, you need to write the server-side JavaScript code to handle connections, disconnections, and incoming messages. To do this, you need to add the following code to the `index.js `file:

```
const io = require('socket.io')(http);

io.on('connection', (socket) => {
  console.log('User is online.');

  socket.on('message', (message) => {
    console.log(`Received message: ${message}`);
    io.emit('message', message);
  });

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

```

This code creates a new [Socket.io](http://socket.io/) instance with the http server, listens for incoming connections, and adds event listeners for incoming messages and disconnections. When a new user connects, the code logs a message to the console. When the server receives a `message` event from a client, the code logs the message to the console and emits a `message` event to all connected clients with the message as the payload. When a user disconnects, the code logs a message to the console.


**Start the app by running** `node index.js` **in the terminal**

Picture of `index.html` code

![Client code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1z2thrn1cpjsp5uiv30.png)

Picture of `index.js `code

![Server code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irv80mrjlhekwse412vk.png)

[Full Project On GitHub](https://github.com/KingsleyAmankwah/Real-time-chat-app)

## Conclusion

Finally, In this tutorial we have learnt how to build a real-time chat application using Node.js and Socket.io. We have explained the basic concepts of Node.js and Socket.io and provided a step-by-step guide for building a chat application from scratch. With this knowledge, you can now create your own real-time applications and take your development skills to the next level. Happy coding!