Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

Chat App

A full-stack real-time group chat application. Users can register, log in, and send messages in a shared room. Messages are delivered instantly over WebSockets (Socket.IO) and persisted in MongoDB.

Tech Stack

Layer Technologies
Frontend React 19, Vite, TypeScript, MUI, Tailwind CSS, TanStack Query, Formik, Zod, Socket.IO Client, Axios
Backend Node.js, Express, TypeScript, MongoDB, Mongoose, Socket.IO, JWT, Zod

Project Structure

chat-app/
├── backend/          # Express API + Socket.IO server
│   ├── src/
│   │   ├── auth/     # Register & login
│   │   ├── users/    # User CRUD
│   │   ├── chat/     # Messages, stats, WebSocket handlers
│   │   └── main.ts
│   └── .env.example
├── frontend/         # React SPA
│   ├── src/
│   └── .env.example
└── README.md

Prerequisites

  • Node.js 18+ (20+ recommended)
  • npm (comes with Node.js)
  • MongoDB running locally or a MongoDB Atlas connection string

Quick Start

1. Clone the repository

git clone <your-repo-url>
cd chat-app

2. Set up the backend

cd backend
npm install
cp .env.example .env

Edit backend/.env:

NODE_ENV=development
PORT=8080
MONGO_URI=mongodb://localhost:27017/chat-app
JWT_SECRET=your_jwt_secret_key_here_change_in_production
FRONTEND_ORIGIN=http://localhost:5173

Important: Do not add spaces around = in .env files. FRONTEND_ORIGIN must match your frontend URL for CORS and Socket.IO.

Start the backend:

npm run dev

Server runs at http://localhost:8080

3. Set up the frontend

Open a new terminal:

cd frontend
npm install
cp .env.example .env

frontend/.env (defaults are fine for local dev):

VITE_API_URL=http://localhost:8080

Start the frontend:

npm run dev

App runs at http://localhost:5173

4. Use the app

  1. Open http://localhost:5173/register and create an account.
  2. Log in at http://localhost:5173/login.
  3. You are redirected to the chat home page.
  4. Open a second browser window (or incognito), register another user, and send messages — they appear in real time for all connected users.

Environment Variables

Backend (backend/.env)

Variable Required Description
PORT No Server port (default: 8080)
NODE_ENV No development | production | test
MONGO_URI Yes MongoDB connection string
JWT_SECRET Yes Secret for signing JWT tokens
FRONTEND_ORIGIN Yes Frontend URL for CORS and Socket.IO (e.g. http://localhost:5173)

Frontend (frontend/.env)

Variable Required Description
VITE_API_URL No Backend URL (default: http://localhost:8080)

Never commit .env files. Use .env.example as a template. .env is listed in .gitignore.

Available Scripts

Backend

Command Description
npm run dev Start dev server with hot reload (tsx watch)
npm run build Compile TypeScript to dist/
npm start Run production build (node dist/main.js)
npm run lint Lint source files

Frontend

Command Description
npm run dev Start Vite dev server
npm run build Type-check and build for production
npm run preview Preview production build locally
npm run lint Lint source files

API Reference

Base URL: http://localhost:8080

Auth (public)

Method Endpoint Body
POST /api/auth/register { email, firstName, lastName, password }
POST /api/auth/login { email, password }

Login response includes accessToken — use it as Authorization: Bearer <token> on protected routes.

Users (protected)

Method Endpoint Description
GET /api/users List all users
GET /api/users/:id Get user by ID
PUT /api/users/:id Update own profile
DELETE /api/users/:id Delete own account

Chat (protected)

Method Endpoint Description
GET /api/chat/messages?page=1&limit=30 Fetch messages (newest page first, returned oldest-first)
POST /api/chat/messages Send message { "content": "hello" }
GET /api/chat/stats { totalUsers, totalMessages, onlineCount }

WebSocket (Socket.IO)

Connect with JWT:

import { io } from "socket.io-client";

const socket = io("http://localhost:8080", {
  auth: { token: accessToken },
});
Event Direction Payload
send_message Client → Server { content: string }
new_message Server → Client Full message with sender info
user_online Server → Client { userId, onlineCount }
user_offline Server → Client { userId, onlineCount }

All authenticated users join a single shared "group" room automatically on connect.

Testing with Postman

  1. POST /api/auth/register — create a user.
  2. POST /api/auth/login — copy accessToken from the response.
  3. Set Authorization → Bearer Token on chat requests.
  4. POST /api/chat/messages and GET /api/chat/messages to test HTTP chat.

Postman does not support Socket.IO out of the box; use the web app or a socket.io-client script for real-time testing.

Production Build

# Backend
cd backend
npm run build
npm start

# Frontend
cd frontend
npm run build
npm run preview   # or serve frontend/dist with any static host

Set production environment variables (MONGO_URI, JWT_SECRET, FRONTEND_ORIGIN, VITE_API_URL) to your deployed URLs before building.

Troubleshooting

Issue Fix
CORS errors Ensure FRONTEND_ORIGIN in backend .env exactly matches the frontend URL (no trailing slash mismatch).
Socket not connecting Confirm backend is running, token is valid, and VITE_API_URL points to the backend.
MongoDB connection failed Start local MongoDB (brew services start mongodb-community) or fix MONGO_URI.
401 Unauthorized Log in again; token may be expired (default: 1 day).
Messages not appearing live Check browser console for Socket.IO errors; verify both apps use the same backend URL.

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages