Building a Real-time Chat Application using the MERN Stack

In today’s digital age, real-time communication has become an integral part of our lives. Whether it is for personal or professional purposes, having the ability to chat with others in real-time is essential. With the MERN stack, developers can easily create a powerful and scalable real-time chat application. In this article, we will explore the steps to build a real-time chat application using the MERN stack.

The MERN stack is a popular web development stack that consists of MongoDB, Express.js, React.js, and Node.js. MongoDB is a NoSQL database that stores data in a flexible, JSON-like format. Express.js is a web application framework for Node.js that simplifies the process of building web applications. React.js is a JavaScript library for building user interfaces, and Node.js is a JavaScript runtime environment that allows developers to run JavaScript on the server-side.

To begin building our real-time chat application, we first need to set up our development environment. Make sure you have Node.js and MongoDB installed on your machine. Once you have them installed, create a new directory for your project and navigate to it in your terminal.

Next, we need to initialize a new Node.js project. Open your terminal and run the following command

“`
npm init -y
“`

This command will create a new `package.json` file for your project. The `package.json` file contains metadata about your project and the npm packages it depends on.

Now, let’s install the necessary dependencies for our project. Run the following command to install Express.js and other required packages

“`
npm install express socket.io mongoose
“`

Express.js will be used to create our server, while Socket.IO will handle real-time communication between the server and the client. Mongoose is an Object Data Modeling (ODM) library for MongoDB, which will help us interact with the database.

With our dependencies installed, let’s create the server file. Create a new file called `server.js` and add the following code

“`javascript
const express = require(‘express’);
const http = require(‘http’);
const socketIO = require(‘socket.io’);
const mongoose = require(‘mongoose’);

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

// Connect to MongoDB
mongoose.connect(‘mongodb//localhost/chatApp’, { useNewUrlParser true })
.then(() => console.log(‘MongoDB Connected’))
.catch(err => console.log(err));

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

This code sets up our server, connects to the MongoDB database, and starts listening for incoming connections on the specified port.

Next, let’s create the models for our chat application. Create a new directory called `models` and inside it, create a new file called `Message.js`. Add the following code to define the `Message` model

“`javascript
const mongoose = require(‘mongoose’);

const messageSchema = new mongoose.Schema({
text {
type String,
required true
},
user {
type String,
required true
},
timestamp {
type Date,
default Date.now
}
});

module.exports = mongoose.model(‘Message’, messageSchema);
“`