DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

Using WebSockets in MERN for Real-Time Chat Applications

Real-time chat applications have become a crucial part of modern web experiences. Whether it’s a customer support system, gaming chat, or collaborative workspaces, real-time communication enhances user engagement. WebSockets provide a powerful way to enable real-time bi-directional communication between a client and a server. In this blog, we’ll explore how to integrate WebSockets into a MERN (MongoDB, Express.js, React, Node.js) application to build a real-time chat feature.


Why Use WebSockets?

WebSockets provide full-duplex communication, allowing the server and client to send and receive messages without continuous HTTP requests. Benefits include:

  • Low latency: Messages are delivered instantly without polling.
  • Efficient resource usage: Reduces unnecessary network requests.
  • Scalability: Enables real-time features across multiple users.

Setting Up WebSockets in a MERN App

1. Install Dependencies

Ensure you have Node.js and npm installed. You’ll need socket.io for WebSockets communication.

npm install express socket.io cors mongoose
Enter fullscreen mode Exit fullscreen mode

For the frontend, install the socket.io-client package:

npm install socket.io-client
Enter fullscreen mode Exit fullscreen mode

2. Backend Implementation (Node.js + Express + Socket.io)

Create an index.js file and set up an Express server with WebSockets.

import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
import cors from 'cors';

const app = express();
const server = createServer(app);
const io = new Server(server, {
    cors: {
        origin: 'http://localhost:3000',
        methods: ['GET', 'POST']
    }
});

app.use(cors());

io.on('connection', (socket) => {
    console.log('A user connected:', socket.id);

    socket.on('sendMessage', (message) => {
        io.emit('receiveMessage', message);
    });

    socket.on('disconnect', () => {
        console.log('User disconnected:', socket.id);
    });
});

server.listen(5000, () => {
    console.log('Server running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

3. Frontend Implementation (React + Socket.io Client)

Create a Chat.js component to handle real-time chat interactions.

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 [chat, setChat] = useState([]);

    useEffect(() => {
        socket.on('receiveMessage', (msg) => {
            setChat((prev) => [...prev, msg]);
        });
    }, []);

    const sendMessage = () => {
        socket.emit('sendMessage', message);
        setMessage('');
    };

    return (
        <div>
            <div>
                {chat.map((msg, index) => (
                    <p key={index}>{msg}</p>
                ))}
            </div>
            <input
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
            />
            <button onClick={sendMessage}>Send</button>
        </div>
    );
};

export default Chat;
Enter fullscreen mode Exit fullscreen mode

4. Running the Application

Start the backend server:

node index.js
Enter fullscreen mode Exit fullscreen mode

Start the frontend React application:

npm start
Enter fullscreen mode Exit fullscreen mode

Your real-time chat application is now functional! Open multiple browser tabs and test sending messages between them.


Scaling WebSockets with MongoDB

If you need to store chat history, integrate MongoDB with Mongoose to save and retrieve messages.

Example MongoDB schema:

import mongoose from 'mongoose';

const MessageSchema = new mongoose.Schema({
    text: String,
    timestamp: { type: Date, default: Date.now }
});

const Message = mongoose.model('Message', MessageSchema);
export default Message;
Enter fullscreen mode Exit fullscreen mode

Modify the sendMessage event to save messages:

socket.on('sendMessage', async (message) => {
    const newMessage = new Message({ text: message });
    await newMessage.save();
    io.emit('receiveMessage', message);
});
Enter fullscreen mode Exit fullscreen mode

Deploying Your WebSocket-Based MERN Chat App

Backend Deployment

  • Use Railway, Render, or Vercel to deploy the Node.js backend.
  • Ensure WebSocket ports are correctly configured.

Frontend Deployment

  • Deploy your React frontend on Netlify or Vercel.
  • Update the WebSocket server URL to match the deployed backend.

Conclusion

WebSockets make real-time communication seamless in a MERN stack application. With socket.io, you can quickly implement a robust chat system with low latency and high efficiency. For production, consider scaling with Redis and a WebSocket load balancer.

Would you like to see additional features, such as user authentication or group chats? Let me know in the comments!

If you enjoy my content and would like to support my work, you can buy me a coffee. Your support is greatly appreciated!

Disclaimer: This content has been generated by AI.

Top comments (2)

Collapse
 
zethix profile image
Andrey Rusev

Disclaimer: This content has been generated by AI.

I like you did this! Few people do it

Collapse
 
nadim_ch0wdhury profile image
Nadim Chowdhury

thanksss