Real-Time Chat App Using MEAN and WebSockets
Creating a real-time chat app using the MEAN stack (MongoDB, Express.js, Angular, Node.js) and WebSockets is a great way to build scalable, full-stack applications with live communication features.
Here’s a step-by-step guide to building a real-time chat app using MEAN + WebSockets (via Socket.IO):
π§± 1. Project Structure
pgsql
Copy
Edit
chat-app/
├── backend/
│ ├── server.js
│ ├── routes/
│ ├── models/
│ └── sockets/
├── frontend/
│ └── Angular project files (generated by Angular CLI)
π§ 2. Backend Setup (Node.js + Express + Socket.IO)
a. Initialize Backend
bash
Copy
Edit
mkdir backend && cd backend
npm init -y
npm install express socket.io mongoose cors
b. Create server.js
js
Copy
Edit
const express = require('express');
const http = require('http');
const cors = require('cors');
const { Server } = require('socket.io');
const mongoose = require('mongoose');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
},
});
app.use(cors());
app.use(express.json());
// MongoDB setup
mongoose.connect('mongodb://localhost:27017/chat', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Chat message model
const Message = mongoose.model('Message', {
username: String,
message: String,
timestamp: Date,
});
// Socket.IO connection
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
socket.on('send-message', async (data) => {
const newMessage = new Message({
username: data.username,
message: data.message,
timestamp: new Date(),
});
await newMessage.save();
io.emit('receive-message', newMessage);
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
π 3. Frontend Setup (Angular + Socket.IO Client)
a. Generate Angular App
bash
Copy
Edit
ng new frontend --routing=false --style=css
cd frontend
npm install socket.io-client
b. Create Chat Service (chat.service.ts)
ts
Copy
Edit
import { Injectable } from '@angular/core';
import { io, Socket } from 'socket.io-client';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ChatService {
private socket: Socket;
private readonly URL = 'http://localhost:3000';
constructor() {
this.socket = io(this.URL);
}
sendMessage(msg: { username: string; message: string }) {
this.socket.emit('send-message', msg);
}
getMessages(): Observable<any> {
return new Observable((observer) => {
this.socket.on('receive-message', (data) => {
observer.next(data);
});
});
}
}
c. Create Chat Component
bash
Copy
Edit
ng generate component chat
d. Update chat.component.ts
ts
Copy
Edit
import { Component, OnInit } from '@angular/core';
import { ChatService } from '../chat.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
})
export class ChatComponent implements OnInit {
username = '';
message = '';
messages: any[] = [];
constructor(private chatService: ChatService) {}
ngOnInit(): void {
this.chatService.getMessages().subscribe((msg) => {
this.messages.push(msg);
});
}
send() {
if (this.username && this.message) {
this.chatService.sendMessage({ username: this.username, message: this.message });
this.message = '';
}
}
}
e. Add Template (chat.component.html)
html
Copy
Edit
<div class="chat-container">
<input [(ngModel)]="username" placeholder="Your name" />
<div class="messages">
<div *ngFor="let msg of messages">
<strong>{{ msg.username }}:</strong> {{ msg.message }}
</div>
</div>
<input [(ngModel)]="message" (keyup.enter)="send()" placeholder="Type a message" />
<button (click)="send()">Send</button>
</div>
f. Import FormsModule in app.module.ts
ts
Copy
Edit
import { FormsModule } from '@angular/forms';
@NgModule({
...
imports: [
BrowserModule,
FormsModule,
...
],
})
export class AppModule {}
π§ͺ 4. Run and Test
Start MongoDB: mongod
Start backend: node server.js
Start frontend: ng serve
Open http://localhost:4200 in multiple browser tabs to test real-time messaging.
π 5. Optional Features to Add
Feature Description
User authentication Add login and session management
Chat rooms Create private/public rooms
Message persistence Load old messages on startup
Typing indicators Show when users are typing
Notifications Browser or in-app alerts
Emoji support Add emoji picker to messages
✅ Summary
Node.js + Express handles the server and WebSocket communication.
MongoDB stores chat messages.
Socket.IO enables real-time bidirectional communication.
Angular provides a reactive front-end UI.
Learn MEAN Stack Course
Read More
Build a To-Do App Using the MEAN Stack
π Mini Project Ideas to Blog About
Handling File Uploads in a MEAN App (e.g., with Multer)
Best Practices for Structuring a MEAN Stack Project
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment