Chat App
Chat App
Project Overview
Step-by-Step Implementation
mkdir chat-app
cd chat-app
npm init -y
MONGO_URI=mongodb://localhost:27017/chat-app
JWT_SECRET=your_jwt_secret
PORT=5000
dotenv.config();
// Middleware
app.use(express.json());
app.use(helmet());
app.use(cors());
windowMs: 15 * 60 * 1000,
max: 100,
});
app.use(limiter);
// Connect to MongoDB
app.listen(port, () => {
});
});
// Hash password before saving the user
next();
});
};
// Register User
router.post('/register', [
check('username').notEmpty().withMessage('Username is required'),
try {
await user.save();
} catch (err) {
console.log(err);
});
// Login User
router.post('/login', [
check('password').notEmpty().withMessage('Password is required')
try {
} catch (err) {
console.log(err);
});
module.exports = router;
Step 6: Set Up Chat Functionality with Socket.io
const io = socketIo(server);
});
socket.on('disconnect', () => {
});
});
// Start server
server.listen(port, () => {
You can create a simple HTML page to interact with the backend. Here’s a
minimal frontend using Socket.io-client:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat App</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Chat App</h1>
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const li = document.createElement('li');
li.textContent = msg;
document.getElementById('messages').appendChild(li);
});
function sendMessage() {
socket.emit('chatMessage', message);
</script>
</body>
</html>
node server.js
3. Open the HTML file in the browser and use multiple tabs to simulate
different users.
---
Conclusion
In this project, we've built a simple chat application with the following: