Skip to content

A full-stack realtime chat app built with React, Node.js, Express, MongoDB, and Socket.IO. The app features real-time private messaging, online user tracking, JWT authentication, and notifications, using custom APIs, context API, and custom hooks for global state management.

Notifications You must be signed in to change notification settings

YashChavanWeb/Websockets-Chat-Application-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Realtime Chat Application

A full-stack realtime chat app built with React, Node.js, Express, MongoDB, and Socket.IO. The app features real-time private messaging, online user tracking, JWT authentication, and notifications, using custom APIs, context API, and custom hooks for global state management.


πŸš€ Features Overview

  • Authentication: Secure login and registration via JWT
  • Realtime Messaging: Bi-directional communication with Socket.IO
  • State Management: Using Context API and custom hooks
  • RESTful APIs: Powered by Express.js
  • Notifications: Instant in-app alerts for new messages
  • Custom Hooks: For API calls, state updates, and effects
  • Online Users: Real-time online/offline status

πŸ‘œ Assets

Demo Video: Watch

Postman Collection: Download here


🧩 Tech Stack

Frontend

  • React (Vite)
  • React Router DOM
  • Context API & Hooks
  • Bootstrap + Google Fonts
  • Socket.IO Client

Backend

  • Node.js + Express.js
  • MongoDB + Mongoose
  • JWT Authentication
  • Socket.IO Server

πŸ”§ Backend Setup

Installation

npm install express mongoose dotenv cors jsonwebtoken bcrypt socket.io

Structure

  • /models
  • /routes
  • /controllers

Authentication Flow

  • Hash passwords in User model

  • Endpoints:

    • POST /register
    • POST /login
    • GET /users/:id
    • GET /users
  • Secure routes with JWT

Fig1: Authentication

alt text

Chat Functionality

  • Chat schema includes members: [userId]

  • Endpoints:

    • POST /chats
    • GET /chats/:userId
    • GET /chats

Fig2: User Chats

alt text

Message Functionality

  • Message schema includes chatId, senderId, text, timestamp

  • Endpoints:

    • POST /messages
    • GET /messages/:chatId

Fig3: Send Messages

alt text


🌐 Frontend Setup

Initialize App

npm create vite@latest my-chat-app

Pages

  • Login, Register, Home, Chat

Components

  • Navbar, ChatSidebar, ChatBox, UserList

Fig4: ChatBox

alt text

Styling

  • Bootstrap + custom Google Font

πŸ” Auth Context (Context API)

Create Context

import { createContext } from "react";
export const AuthContext = createContext();

Provider Setup

const [user, setUser] = useState(null);
<AuthContext.Provider value={{ user, setUser }}>
  {children}
</AuthContext.Provider>;

Example Usage

const { user } = useContext(AuthContext);

Controlled Inputs with useCallback

const updateRegisterInfo = useCallback((info) => {
  setRegisterInfo(info);
}, []);

πŸ”Œ Connecting Frontend to Backend

API Utility Function

const data = await response.json();
if (!response.ok) {
  return { error: true, message: data.message || data };
}
return data;

Auth State

const [registerInfo, setRegisterInfo] = useState({
  name: "",
  email: "",
  password: "",
});

Call Auth Functions

const { registerUser, registerError, isRegisterLoading } =
  useContext(AuthContext);
<Form onSubmit={registerUser}>
  {registerError?.error && <Alert>{registerError.message}</Alert>}
</Form>;

πŸ’¬ Chat Functionality (Frontend)

Global State with ChatContext

  • Manage:

    • Current chat
    • Messages
    • Notifications

Chat UI

  • Sidebar: Existing chats + users
  • Main: Messages + input field

Fig5 : New Users

alt text

Fig6: Realtime Messages

alt text

Message Handling

  • Custom hook for fetching messages
  • Scroll to last message using useRef
const scrollRef = useRef();
useEffect(() => {
  scrollRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);

πŸ›°οΈ Socket.IO Integration

REST API vs WebSocket

REST API WebSocket
Stateless Stateful
Unidirectional Bidirectional
Request-Response Event-driven
Multiple TCP Connections Single Persistent TCP

Server Socket.IO Setup

  • Initialize socket.io on Express

  • Events:

    • connection
    • sendMessage
    • getMessage
    • getNotification

Fig7: Socket Connection

alt text

Frontend Socket Setup

const socket = useRef();
useEffect(() => {
  socket.current = io("http://localhost:PORT");
  socket.current.emit("newUser", user._id);
}, []);

Fig7: Online Users

alt text

Message & Notification Handling

socket.current.on("getMessage", (message) => {
  setMessages((prev) => [...prev, message]);
});

socket.current.on("getNotification", (res) => {
  const isChatOpen = currentChat?.members.includes(res.senderId);
  setNotifications((prev) => [{ ...res, isRead: isChatOpen }, ...prev]);
});

Fig8: Notifications

alt text


πŸ› οΈ Potential Extensions

  • Group Chats
  • Media Sharing
  • Typing Indicators
  • Read Receipts

About

A full-stack realtime chat app built with React, Node.js, Express, MongoDB, and Socket.IO. The app features real-time private messaging, online user tracking, JWT authentication, and notifications, using custom APIs, context API, and custom hooks for global state management.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published