Building a Chat Application with User & Admin Panel using MERN Stack Print

  • 1

Building a Chat Application with User & Admin Panel using MERN Stack on DomainIndia.com VPS with AlmaLinux 8.6

Introduction:

In this article, we will be building a chat application with a user and admin panel using the MERN stack (MongoDB, Express, React, and Node.js). We will develop the application locally on Visual Studio Code and deploy it on a VPS provided by DomainIndia.com running AlmaLinux 8.6.

Here's an outline of the steps we will follow:

1. Setting Up the Application
2. Setting Up the Node Server
3. Creating the Routes
4. Defining the Models
5. Connecting to a Database
6. Testing the API
7. Creating the Frontend
8. Running the React App
9. Creating the React Components

1. Setting Up the Application:

First, let's set up the application on our local machine.

- Install Node.js from the official website (https://nodejs.org/).
- Install Visual Studio Code (https://code.visualstudio.com/).
- Open Visual Studio Code and create a new folder for your project.
- Open a terminal in Visual Studio Code and run the following command to create a new Node.js project:


npm init -y

2. Setting Up the Node Server:

- Install the required dependencies for the server:


npm install express mongoose cors body-parser

- Create a new file called `server.js` and add the following code to set up the server:


const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// Database connection and server start
mongoose.connect('mongodb://localhost/chat-app', { useNewUrlParser: true, useUnifiedTopology: true });

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to the database');
app.listen(5000, () => console.log('Server is running on port 5000'));
});

3. Creating the Routes:

- Create a new folder called `routes` and add a new file called `userRoutes.js` for user-related routes.
- Add the following code to `userRoutes.js`:


const express = require('express');
const router = express.Router();
const UserController = require('../controllers/UserController');

// Add user routes
router.post('/register', UserController.register);
router.post('/login', UserController.login);

module.exports = router;

- Do the same for the admin panel by creating `adminRoutes.js`.

4. Defining the Models:

- Create a new folder called `models` and add a new file called `User.js` for the user model.
- Add the following code to `User.js`:


const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
isAdmin: { type: Boolean, default: false },
});

module.exports = mongoose.model('User', UserSchema);

5. Connecting to a Database:

- Sign up for a MongoDB account (https://www.mongodb.com/) and create a new cluster.
- Add the connection string to your `server.js` file:


mongoose.connect('<YOUR_MONGODB_CONNECTION_STRING>', { useNewUrlParser: true, useUnifiedTopology: true });

6. Testing the API:

- Install Postman (https://www.postman.com/) to test your API endpoints.
- Test the user registration and login routes by sending POST requests to the following URLs:


http://localhost:5000/register
http://localhost:5000/login

7. Creating the Frontend:

- Install the Create React App CLI tool globally:


npm install -g create-react-app

- Create a new React app in your project folder:


create-react-app client

- Change to the `client` directory and install required dependencies:


cd client
npm install axios react-router-dom

8. Running the React App:

- Start the development server by running the following command in the `client` folder:


npm start

- The React app should now be running on `http://localhost:3000`.

9. Creating the React Components:

- Create the following components in the `client/src/components` folder:

a. `Navbar.js`: A navigation bar for the chat application.

import React from 'react';
import { Link } from 'react-router-dom';

const Navbar = () => {
return (
<nav>
<div>
<Link to="/">ChatApp</Link>
</div>
<div>
<Link to="/login">Login</Link>
<Link to="/register">Register</Link>
<Link to="/chat">Chat</Link>
<Link to="/admin">Admin</Link>
</div>
</nav>
);
};

export default Navbar;

b. `Login.js`: A login form for users to log in.

import React, { useState } from 'react';
import axios from 'axios';

const Login = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/login', { username, password });
console.log(response.data);
} catch (error) {
console.error(error);
}
};

return (
<form onSubmit={handleSubmit}>
<label>Username:</label>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
<label>Password:</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
</form>
);
};

export default Login;

c. `Register.js`: A registration form for users to sign up.

import React, { useState } from 'react';
import axios from 'axios';

const Register = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post('/api/register', { username, password });
console.log(response.data);
} catch (error) {
console.error(error);
}
};

return (
<form onSubmit={handleSubmit}>
<label>Username:</label>
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
<label>Password:</label>
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Register</button>
</form>
);
};

export default Register;

d. `Chat.js`: The main chat component where users can send and receive messages.

import React from 'react';

const Chat = () => {
return (
<div>
<h1>Chat</h1>
{/* Add chat functionality here */}
</div>
);
};

export default Chat;

e. `Admin.js`: The admin panel for managing users and chat rooms.

import React from 'react';

const Admin = () => {
return (
<div>
<h1>Admin Panel</h1>
{/* Add admin functionality here */}
</div>
);
};

export default Admin;

- Update `client/src/App.js` to include the new components and set up routing using `react-router-dom`:


import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './components/Navbar';
import Login from './components

/Login';
import Register from './components/Register';
import Chat from './components/Chat';
import Admin from './components/Admin';

const App = () => {
return (
<Router>
<Navbar />
<Switch>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/chat" component={Chat} />
<Route path="/admin" component={Admin} />
</Switch>
</Router>
);
};

export default App;

Now that you have created the necessary components and added the routing, your chat application frontend should be functional. You can test the application by running the React development server using `npm start` in the `client` folder. The application will be accessible at `http://localhost:3000`.

As you continue to develop your chat application, you will need to add more functionality to the `Chat` and `Admin` components. This may include features like real-time messaging using WebSockets, handling user authentication, managing chat rooms, and more. By breaking the application into components and using the power of React and the MERN stack, you can create a scalable and modular chat application that meets your needs.

Your chat application should be fully functional. The next step would be to deploy the application to your DomainIndia.com VPS running AlmaLinux 8.6. To do this, follow the steps provided by DomainIndia to set up the VPS, install Node.js, MongoDB, and any other required software, and configure your application for production.

Once your chat application is live, you can start using it with your friends or colleagues. Enjoy your new MERN stack chat application!

10. Deploying to DomainIndia.com VPS running AlmaLinux 8.6:

To deploy your chat application on DomainIndia.com VPS running AlmaLinux 8.6, follow these steps:

a. Preparing the VPS:

- Purchase a VPS plan from DomainIndia.com and set up AlmaLinux 8.6.
- Connect to your VPS using an SSH client like PuTTY.
- Update the system packages:


sudo dnf update -y

- Install Node.js and npm:


sudo dnf install -y nodejs npm

- Install MongoDB:


sudo dnf install -y mongodb-org

- Start and enable MongoDB service:


sudo systemctl start mongod
sudo systemctl enable mongod

b. Deploying the Backend:

- Clone your chat application repository from your VCS (e.g., GitHub) to your VPS:


git clone <your_repository_url>

- Change to your project directory and install the backend dependencies:


cd <your_project_directory>
npm install

- Update the MongoDB connection string in `server.js` to point to the VPS's local MongoDB instance:


mongoose.connect('mongodb://localhost/chat-app', { useNewUrlParser: true, useUnifiedTopology: true });

- Set up a process manager like PM2 to keep the Node.js server running in the background:


sudo npm install -g pm2
pm2 start server.js
pm2 save
pm2 startup

c. Deploying the Frontend:

- Change to the `client` directory and install the frontend dependencies:


cd client
npm install

- Build the React app for production:


npm run build

- Install and configure a web server like Nginx to serve the static frontend files:


sudo dnf install -y nginx

- Create a new Nginx server block configuration file at `/etc/nginx/conf.d/chatapp.conf`:


server {
listen 80;
server_name yourdomain.com;

location / {
root /path/to/your/project/client/build;
try_files $uri /index.html;
}

location /api {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

- Replace `yourdomain.com` with your actual domain name and `/path/to/your/project/client/build` with the absolute path to the `build` directory.

- Restart Nginx and enable it to start on boot:


sudo systemctl restart nginx
sudo systemctl enable nginx

d. Configure DNS:

- Log in to your DomainIndia account and configure the DNS settings to point your domain name to your VPS's IP address.

Once everything is set up, your chat application should be accessible at your domain name. Test the application to ensure that everything is working as expected. You have now successfully deployed your MERN stack chat application with a user and admin panel on a DomainIndia.com VPS running AlmaLinux 8.6.

11. Securing the Application with SSL:

To improve the security of your chat application, it's essential to encrypt the communication between the server and clients using SSL (Secure Sockets Layer). In this step, we'll use Let's Encrypt and Certbot to obtain a free SSL certificate and configure Nginx to serve your application over HTTPS.

a. Installing Certbot:

- First, enable the EPEL repository:


sudo dnf install -y epel-release

- Install Certbot and the Nginx plugin:


sudo dnf install -y certbot python3-certbot-nginx

b. Obtaining the SSL Certificate:

- Run the following command to obtain and install the SSL certificate for your domain:


sudo certbot --nginx -d yourdomain.com

- Replace `yourdomain.com` with your actual domain name.

- Follow the on-screen instructions to complete the process. Certbot will automatically modify your Nginx configuration file to enable HTTPS.

c. Automatic Renewal:

- Let's Encrypt SSL certificates are valid for 90 days. To automatically renew the certificates before they expire, add a cron job or a systemd timer.

- Open the crontab for the root user:


sudo crontab -e

- Add the following line to schedule a daily check for certificate renewal:


0 3 * * * /usr/bin/certbot renew --quiet

- Save the file and exit. The cron job will attempt to renew the certificates daily at 3 AM.

Now, your chat application should be accessible over HTTPS. Test the application to ensure that everything is working correctly, and verify that the connection is encrypted using an SSL certificate.

With your MERN stack chat application with a user and admin panel secured with SSL and deployed on a DomainIndia.com VPS running AlmaLinux 8.6, you've successfully built and deployed a robust, secure, and scalable chat solution. You can now confidently share your chat application with users, knowing that their communication will be encrypted and protected.

12. Monitoring and Maintaining the Application:

Now that your chat application is deployed and secured, it's crucial to monitor its performance and maintain it to ensure a smooth user experience. This section will discuss some best practices for monitoring, maintaining, and troubleshooting your application.

a. Monitoring Application Performance:

- Keep an eye on your server resources like CPU, memory, and disk usage. You can use tools like `htop`, `top`, or `glances` to monitor the server in real-time.
- Monitor the logs for any errors or unusual activity. Check the logs regularly for both Nginx (`/var/log/nginx/error.log` and `/var/log/nginx/access.log`) and your Node.js application (logs managed by PM2, accessible via `pm2 logs`).
- Set up alerts to notify you when the server is running low on resources or experiencing downtime. Third-party monitoring services like UptimeRobot, Pingdom, or Datadog can help with this.

b. Maintaining Application Security:

- Regularly update your server packages and software, including Node.js, npm, MongoDB, and Nginx, to ensure you're running the latest versions with security patches.
- Make sure to update your application dependencies as well, both on the frontend and backend, to mitigate any potential security risks.
- Perform regular security audits using tools like OWASP ZAP or security plugins in your CI/CD pipeline to identify and address vulnerabilities in your application.

c. Scaling the Application:

- Monitor your application's usage and be prepared to scale the infrastructure as needed. Vertical scaling (increasing the server resources like CPU, memory, or storage) and horizontal scaling (adding more servers) are options to consider when traffic increases.
- Optimize the application code for better performance by identifying and addressing bottlenecks, using caching mechanisms, or implementing load balancing.

d. Troubleshooting Common Issues:

- If the application is not loading, check the status of Nginx and the Node.js server managed by PM2. Restart the services if needed.
- Check the logs for any errors or unusual activity, which can help identify the root cause of the issue.
- Make sure the SSL certificates are up to date and that the renewal process is working as expected.
- If you encounter issues with MongoDB, check its logs at `/var/log/mongodb/mongod.log` and investigate any reported errors.

By closely monitoring your chat application's performance, maintaining its security, and addressing potential issues, you can ensure that your MERN stack chat application remains reliable and enjoyable for your users.


Was this answer helpful?

« Back