npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@anoopgeorgebits/realtime-chat-app

v0.1.2

Published

A real-time chat application built with MERN stack and Socket.io

Readme

Real-time Chat Application 💬

A full-stack real-time chat application built with the MERN stack (MongoDB, Express.js, React.js, Node.js) and Socket.io for WebSocket communication.

License Node React CI Status

🏗️ Architecture

System Architecture Overview

┌─────────────────┐         WebSocket/HTTP        ┌─────────────────┐
│                 │◄──────────────────────────────►│                 │
│  React Client   │         Socket.io              │  Express Server │
│   (Frontend)    │         REST API               │   (Backend)     │
│                 │                                 │                 │
└─────────────────┘                                 └────────┬────────┘
                                                             │
                                                             │ Mongoose
                                                             │
                                                    ┌────────▼────────┐
                                                    │                 │
                                                    │    MongoDB      │
                                                    │   (Database)    │
                                                    │                 │
                                                    └─────────────────┘

Technology Stack

Frontend

  • React.js 18 - UI library for building interactive interfaces
  • Socket.io-client - Real-time bidirectional event-based communication
  • Axios - HTTP client for REST API calls
  • React Router - Client-side routing
  • CSS3 - Styling with modern gradient designs

Backend

  • Node.js - JavaScript runtime environment
  • Express.js - Web application framework
  • Socket.io - WebSocket library for real-time communication
  • Mongoose - MongoDB object modeling tool
  • JWT - JSON Web Tokens for authentication
  • bcryptjs - Password hashing

Database

  • MongoDB - NoSQL document database
    • Collections:
      • users - User accounts and profiles
      • messages - Chat messages with timestamps
      • rooms - Chat rooms with members

✨ Features

Core Features

  • User Authentication - Register, login, logout with JWT
  • Real-time Messaging - Instant message delivery using WebSocket
  • Multiple Chat Rooms - Create and join different chat rooms
  • Online Users - See who's currently in the room
  • Typing Indicators - Know when someone is typing
  • Message History - Persistent message storage in MongoDB
  • User Presence - Join/leave notifications
  • Responsive Design - Works on desktop and mobile devices

Security Features

  • 🔒 Password hashing with bcrypt
  • 🔒 JWT-based authentication
  • 🔒 Protected API routes
  • 🔒 Input validation

📋 Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v14 or higher) - Download
  • MongoDB (v4 or higher) - Download
  • npm or yarn - Comes with Node.js

🚀 Installation & Setup

1. Clone the repository

git clone https://github.com/yourusername/realtime-chat-app.git
cd realtime-chat-app

2. Install dependencies

Install both server and client dependencies:

# Install server dependencies
npm install

# Install client dependencies
cd client
npm install
cd ..

Or use the convenience script:

npm run install-all

3. Configure environment variables

Create a .env file in the root directory:

cp .env.example .env

Edit the .env file with your configuration:

PORT=5000
MONGODB_URI=mongodb://localhost:27017/realtime-chat
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
NODE_ENV=development
CLIENT_URL=http://localhost:3000

4. Start MongoDB

Make sure MongoDB is running on your system:

# On Windows (if installed as service)
net start MongoDB

# On macOS/Linux
mongod

# Or using MongoDB Compass (GUI)

5. Run the application

Development mode (runs both server and client):

npm run dev-all

Or run separately:

Terminal 1 - Backend:

npm run dev

Terminal 2 - Frontend:

npm run client

Production mode:

# Build the React app
cd client
npm run build
cd ..

# Start the server
npm start

The application will be available at:

  • Frontend: http://localhost:3000
  • Backend API: http://localhost:5000

📁 Project Structure

realtime-chat-app/
├── client/                      # React frontend
│   ├── public/
│   │   └── index.html
│   ├── src/
│   │   ├── components/
│   │   │   ├── Auth/
│   │   │   │   ├── Login.js
│   │   │   │   └── Register.js
│   │   │   └── Chat/
│   │   │       ├── ChatRoom.js
│   │   │       ├── ChatRoom.css
│   │   │       ├── RoomList.js
│   │   │       └── RoomList.css
│   │   ├── App.js
│   │   ├── App.css
│   │   ├── index.js
│   │   └── index.css
│   └── package.json
│
├── server/                      # Express backend
│   ├── models/
│   │   ├── User.js             # User schema
│   │   ├── Message.js          # Message schema
│   │   └── Room.js             # Room schema
│   ├── routes/
│   │   ├── auth.js             # Authentication routes
│   │   ├── messages.js         # Message routes
│   │   └── rooms.js            # Room routes
│   ├── middleware/
│   │   └── auth.js             # JWT authentication middleware
│   └── server.js               # Main server file
│
├── .env.example                 # Environment variables template
├── .gitignore                   # Git ignore file
├── package.json                 # Server dependencies
└── README.md                    # This file

🔌 API Endpoints

Authentication

  • POST /api/auth/register - Register a new user
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user (protected)
  • POST /api/auth/logout - Logout user (protected)

Rooms

  • GET /api/rooms - Get all public rooms (protected)
  • POST /api/rooms - Create a new room (protected)
  • GET /api/rooms/:roomName - Get room details (protected)
  • POST /api/rooms/:roomName/join - Join a room (protected)
  • POST /api/rooms/:roomName/leave - Leave a room (protected)

Messages

  • GET /api/messages/room/:roomName - Get messages for a room (protected)
  • PUT /api/messages/:messageId - Edit a message (protected)
  • DELETE /api/messages/:messageId - Delete a message (protected)

🔄 Socket Events

Client → Server

  • join - Join a chat room
  • send_message - Send a message to the room
  • typing - Notify that user is typing
  • stop_typing - Notify that user stopped typing
  • disconnect - User disconnects

Server → Client

  • receive_message - Receive a new message
  • user_joined - Notification when user joins
  • user_left - Notification when user leaves
  • room_users - Updated list of users in room
  • user_typing - Someone is typing
  • user_stop_typing - Someone stopped typing

🗄️ Database Schema

User Model

{
  username: String (required, unique),
  email: String (required, unique),
  password: String (required, hashed),
  avatar: String,
  status: String (online/offline/away),
  createdAt: Date
}

Message Model

{
  room: String (required),
  sender: ObjectId (ref: User),
  senderName: String,
  content: String (required),
  type: String (text/image/file),
  timestamp: Date,
  edited: Boolean,
  editedAt: Date
}

Room Model

{
  name: String (required, unique),
  description: String,
  type: String (public/private),
  creator: ObjectId (ref: User),
  members: [ObjectId] (ref: User),
  createdAt: Date,
  lastActivity: Date
}

🎨 UI Features

  • Modern gradient design with purple/blue theme
  • Smooth animations for messages and interactions
  • Responsive layout adapts to screen size
  • Real-time updates without page refresh
  • Typing indicators show user activity
  • Online user list with avatars
  • Message timestamps for context
  • System notifications for user joins/leaves

🔒 Security Best Practices

  1. Password Security

    • Passwords are hashed using bcrypt with salt rounds
    • Never stored in plain text
  2. Authentication

    • JWT tokens expire after 7 days
    • Tokens stored in localStorage (consider httpOnly cookies for production)
    • Protected routes require valid token
  3. Input Validation

    • Server-side validation using express-validator
    • Sanitization of user inputs
  4. Environment Variables

    • Sensitive data stored in .env file
    • .env file excluded from version control

🚀 Deployment

Deploy to Heroku

  1. Create a Heroku app:
heroku create your-app-name
  1. Set environment variables:
heroku config:set JWT_SECRET=your_secret_key
heroku config:set MONGODB_URI=your_mongodb_connection_string
  1. Deploy:
git push heroku main

Deploy Frontend to Vercel/Netlify

Build the React app and deploy the client/build directory.

Database Hosting

Consider using MongoDB Atlas for cloud-hosted MongoDB.

🧪 Testing

This project includes comprehensive test coverage for both backend and frontend.

Test Summary

  • 6 tests passing
  • Backend: 4 tests (Authentication API)
  • Frontend: 2 tests (Login Component)
  • Code Coverage: 51.61% overall, 74% for auth routes

Run Tests

# Run backend tests
npm run test:backend

# Run frontend tests
cd client
npm test -- --watchAll=false

# Run all tests
npm run test:all

Test Details

See TESTING.md for complete test documentation including:

  • Detailed test case descriptions
  • Expected results and assertions
  • Code coverage reports
  • Instructions for adding new tests

🔄 CI/CD Pipeline

This project uses GitHub Actions for continuous integration and deployment.

Automated Checks

The CI pipeline runs automatically on every push and pull request:

Backend Tests - Jest + Supertest unit tests
Frontend Tests - React Testing Library component tests
Build Verification - Ensures React app builds successfully
Code Linting - ESLint checks for code quality
Multi-Version Testing - Tests on Node.js 18.x and 20.x

Workflow Status

CI Status

Run Linting Locally

# Backend linting
npm run lint:backend

# Frontend linting
cd client && npm run lint

# Auto-fix linting issues
npm run lint:fix
cd client && npm run lint:fix

CI/CD Documentation

See CI_CD_DOCUMENTATION.md for:

  • Complete workflow configuration
  • Job details and dependencies
  • Troubleshooting guide
  • Best practices

📝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🤝 Acknowledgments

  • Socket.io for real-time communication
  • MongoDB for flexible data storage
  • React community for excellent documentation
  • All contributors who participate in this project

📧 Contact

For questions or support, please open an issue on GitHub.


Happy Chatting! 💬🚀