Real-time Chat App with React, Node.js, and Socket.io | asadmukhtar.info
Step-by-Step Guide to Setting Up Authentication in Laravel 12 with Breeze   |   Manual Authentication in Laravel 12: Step-by-Step Guide   |   How to Build a REST API in Laravel 12 with Sanctum   |   Laravel 12 CRUD Application with Image Upload   |   Laravel 12 Multi-Auth System: Admin & User Login   |   How to Integrate Stripe Payment Gateway in Laravel 12   |   Building a Role-Based Access Control (RBAC) in Laravel 12   |   How to Use Laravel 12 Queues and Jobs for Background Tasks   |   Laravel 12 Livewire CRUD Example with Validation   |   Email Verification and Password Reset in Laravel 12   |   How to Use Laravel 12 API with Vue.js 3   |   Laravel 12 AJAX CRUD with jQuery and Bootstrap   |   Laravel 12 Multi-Language Website Setup   |   React Best Practices for 2025: Performance, SEO, and Scalability   |   How to Build a Full-Stack MERN App: A Step-by-Step Guide   |   React State Management: Redux vs. Context API vs. Recoil   |   Server-Side Rendering (SSR) in React with Next.js for SEO   |   How to Optimize React Apps for Faster Load Times   |   Building a REST API with Node.js and Express for a React App   |   Integrating JWT Authentication in React and Node.js (MERN Stack)   |   Real-time Chat App with React, Node.js, and Socket.io   |   How to Deploy a MERN Stack Application on AWS or Vercel   |   Connecting React Frontend to a Node.js Backend with Axios   |   Laravel Implement Flash Messages Example   |   How to integrate Angular 19 with Node.js and Express for full-stack development   |   Best practices for connecting Angular 19 frontend with Laravel API   |   Step-by-step guide to upgrading an existing project to Angular 19   |   How to implement authentication in Angular 19 using JWT and Firebase   |   Optimizing server-side rendering in Angular 19 with route-level render modes   |   Using Angular 19 signals for state management in large applications   |   How to create standalone components in Angular 19 for modular architecture   |   Building a CRUD application in Angular 19 with MongoDB and Express   |   Implementing lazy loading in Angular 19 to improve performance   |   How to integrate Angular 19 with GraphQL for efficient data fetching   |   Vue 3 Composition API vs Options API: A Comprehensive Comparison   |   Fetching and Displaying Data from APIs in Vue.js with Axios   |   Building a Todo App in Vue.js with Local Storage Integration   |   Handling Forms and Validation in Vue.js Using VeeValidate   |   State Management in Vue.js Applications Using Vuex   |   10 Most Important Tasks Every MERN Stack Developer Should Master   |   How to Build a Full-Stack CRUD App with MERN Stack   |   Best Practices for Authentication & Authorization in MERN Stack   |   1. MEAN Stack vs. MERN Stack: Which One Should You Choose in 2025   |   Top 10 Node.js Best Practices for Scalable and Secure Applications   |   How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)   |   Mastering Angular and Express.js for Full-Stack Web Development   |   Top 10 Daily Tasks Every Frontend Developer Should Practice   |   Essential Backend Development Tasks to Boost Your Coding Skills   |   Real-World Mini Projects for Practicing React.js Daily   |   Laravel Developer Task List: Beginner to Advanced Challenges   |   How to Assign Effective Tasks to Your Intern Developers   |   10 Must-Try Tasks to Master JavaScript Fundamentals   |   Practical CSS Challenges That Improve Your UI Design Skills   |   Top Tasks to Learn API Integration in React and Angular   |   Best Task Ideas for a 30-Day Web Development Challenge   |   Top Git and GitHub Tasks Every Developer Should Know   |   30-Day Task Plan for Web Development Interns   |   Weekly Task Schedule for Junior Developers in a Startup   |   How to Track Progress with Development Tasks for Interns   |   What Tasks Should You Give to Interns in a MERN Stack Project   |   Build These 5 Projects to Master React Routing   |   Task-Based Learning: Become a Full-Stack Developer in 90 Days   |   Daily Coding Tasks That Will Sharpen Your Logical Thinking   |   Top 7 Backend Task Ideas to Practice With Node.js and MongoDB   |  

Real-time Chat App with React, Node.js, and Socket.io

In modern web applications, real-time communication is a highly demanded feature, especially in chat applications. The ability to send and receive messages in real-time enhances the user experience, making apps more interactive and engaging.

In this tutorial, we’ll walk you through building a real-time chat application using React, Node.js, and Socket.io. Socket.io is a popular JavaScript library that enables real-time, bi-directional communication between web clients and servers.

By the end of this tutorial, you'll have a working real-time chat app where multiple users can communicate instantly.

1. Setting Up the Backend with Node.js, Express, and Socket.io

Step 1: Initialize the Node.js Project

  1. Create a new directory for the backend and initialize the project:

mkdir real-time-chat-backend
cd real-time-chat-backend
npm init -y

Install the necessary dependencies: express, http, and socket.io:

npm install express socket.io

Step 2: Create the Basic Server

  1. Create a file server.js for setting up the server:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

app.get('/', (req, res) => {
  res.send('Server is running');
});

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

  // Listen for chat messages
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg); // Emit message to all clients
  });

  socket.on('disconnect', () => {
    console.log('A user disconnected');
  });
});

server.listen(5000, () => {
  console.log('Server is running on http://localhost:5000');
});

Step 3: Run the Backend Server

  1. Start the backend server by running the following command:

node server.js

2. Setting Up the Frontend with React

Step 1: Create a React Application

  1. Create a new React app:

npx create-react-app real-time-chat-frontend
cd real-time-chat-frontend

Install Socket.io-client to communicate with the server:

npm install socket.io-client

Step 2: Create the Chat UI

  1. Inside the src folder, create a new component called Chat.js:

import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:5000'); // Connect to the backend

const Chat = () => {
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);
  const [username, setUsername] = useState('');

  useEffect(() => {
    // Listen for incoming messages from the server
    socket.on('chat message', (msg) => {
      setMessages((prevMessages) => [...prevMessages, msg]);
    });
  }, []);

  const sendMessage = (e) => {
    e.preventDefault();
    if (message.trim()) {
      socket.emit('chat message', `${username}: ${message}`);
      setMessage('');
    }
  };

  return (
    <div className="chat-container">
      <h1>Real-Time Chat</h1>
      <div className="messages">
        {messages.map((msg, index) => (
          <p key={index}>{msg}</p>
        ))}
      </div>
      <form onSubmit={sendMessage}>
        <input
          type="text"
          placeholder="Enter your name"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          required
        />
        <input
          type="text"
          placeholder="Type a message"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          required
        />
        <button type="submit">Send</button>
      </form>
    </div>
  );
};

export default Chat;

Style the components by adding a simple CSS in App.css or inline styles for layout:

.chat-container {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.messages {
  max-height: 400px;
  overflow-y: scroll;
  margin-bottom: 20px;
}

input {
  padding: 10px;
  margin: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

Step 3: Add the Chat Component to App.js

  1. Update App.js to include the Chat component:

import React from 'react';
import './App.css';
import Chat from './Chat';

const App = () => {
  return (
    <div className="App">
      <Chat />
    </div>
  );
};

export default App;

3. Running the Application

Step 1: Run the React App

  1. Start the React frontend by running:

npm start

Step 2: Test the Real-time Chat Functionality

  1. Open the app in multiple browser windows or tabs.
  2. In each window, enter a unique username and send messages.
  3. Messages will be displayed in real-time across all open windows.

4. Enhancing the Chat App

To improve your real-time chat app, consider adding the following features:

  • User Authentication: Implement JWT or other authentication methods to allow users to register, log in, and access private chats.
  • Chat Rooms: Allow users to create and join specific chat rooms.
  • Message Persistence: Store chat messages in a database (e.g., MongoDB) to persist the chat history even after server restarts.
  • Emojis and Media: Implement emoji support and allow sending images, videos, or files.

Conclusion

Building a real-time chat app with React, Node.js, and Socket.io is a great way to understand the power of WebSockets and real-time communication. Socket.io makes it easy to implement real-time, bi-directional communication between the client and server, while React provides a dynamic user interface that updates instantly.

In this tutorial, you learned how to:

  • Set up the backend with Node.js and Socket.io.
  • Build the frontend with React and integrate Socket.io-client for real-time messaging.
  • Test the chat app and explore the possibilities for extending it.

Related Tutorials

How to Build a Full-Stack MERN App: A Step-by-Step Guide
Building a REST API with Node.js and Express for a React App
Integrating JWT Authentication in React and Node.js (MERN Stack)
Real-time Chat App with React, Node.js, and Socket.io
How to Deploy a MERN Stack Application on AWS or Vercel
Connecting React Frontend to a Node.js Backend with Axios
10 Must-Try Tasks to Master JavaScript Fundamentals