In today’s digital world, real-time communication is essential. Whether for business, personal use, or customer service, a web chat application enhances user experience and engagement. In this blog, we will guide you through building a full-featured web chat app using modern technologies. At DVS Web Infotech, we specialize in creating scalable, real-time applications, and we’ll walk you through the key steps to develop your own chat app.
To build an efficient and scalable web chat application, we will use the following technologies:
Create a new Node.js project and install necessary dependencies:
mkdir chat-app-backend && cd chat-app-backend
npm init -y
npm install express socket.io mongoose cors dotenv jsonwebtoken bcryptjs
Create an index.js
file:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, { cors: { origin: '*' } });
app.use(cors());
app.use(express.json());
io.on('connection', (socket) => {
console.log('New user connected');
socket.on('sendMessage', (message) => {
io.emit('receiveMessage', message);
});
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
server.listen(5000, () => console.log('Server running on port 5000'));
Install MongoDB and configure the connection in db.js
:
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
console.log('MongoDB Connected');
} catch (error) {
console.error(error);
}
};
module.exports = connectDB;
const mongoose = require('mongoose');
const MessageSchema = new mongoose.Schema({
sender: String,
message: String,
timestamp: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Message', MessageSchema);
npx create-react-app chat-app-frontend
cd chat-app-frontend
npm install socket.io-client axios
Create Chat.js
in the src
folder:
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:5000');
const Chat = () => {
const [message, setMessage] = useState('');
const [messages, setMessages] = useState([]);
useEffect(() => {
socket.on('receiveMessage', (msg) => {
setMessages([...messages, msg]);
});
}, [messages]);
const sendMessage = () => {
socket.emit('sendMessage', message);
setMessage('');
};
return (
<div>
<h2>Chat Room</h2>
<div>{messages.map((msg, index) => <p key={index}>{msg}</p>)}</div>
<input value={message} onChange={(e) => setMessage(e.target.value)} />
<button onClick={sendMessage}>Send</button>
</div>
);
};
export default Chat;
const UserSchema = new mongoose.Schema({
username: String,
password: String
});
module.exports = mongoose.model('User', UserSchema);
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('./models/User');
const register = async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ username, password: hashedPassword });
await newUser.save();
res.json({ message: 'User registered' });
};
const login = async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ username });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(400).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ id: user._id }, 'secret', { expiresIn: '1h' });
res.json({ token });
};
Use Heroku or AWS to deploy your backend.
git init
git add .
git commit -m "Deploy chat backend"
git push heroku main
Use Vercel or Netlify for frontend deployment.
npm run build
netlify deploy
Congratulations! You have successfully built a full web chat app with real-time messaging, authentication, and database integration. At DVS Web Infotech, we specialize in modern web application development, ensuring security, scalability, and performance.
Start your journey today and build amazing applications with real-time communication!