https://github.com/hassonor/mastering-mern
NodeJS (TS,Redis, Queues, Workers, Jest,Mongoose, Cloudinary, Bunyan, Socket-io, Bull ...)
https://github.com/hassonor/mastering-mern
aws bull bunyan caching cloudinary elasticache jest mongodb mongoose nodejs queues redis socket-io terraform ts workers
Last synced: 2 months ago
JSON representation
NodeJS (TS,Redis, Queues, Workers, Jest,Mongoose, Cloudinary, Bunyan, Socket-io, Bull ...)
- Host: GitHub
- URL: https://github.com/hassonor/mastering-mern
- Owner: hassonor
- License: apache-2.0
- Created: 2022-12-17T10:39:15.000Z (over 3 years ago)
- Default Branch: develop
- Last Pushed: 2023-12-03T21:07:39.000Z (over 2 years ago)
- Last Synced: 2025-01-07T09:43:38.473Z (over 1 year ago)
- Topics: aws, bull, bunyan, caching, cloudinary, elasticache, jest, mongodb, mongoose, nodejs, queues, redis, socket-io, terraform, ts, workers
- Language: TypeScript
- Homepage:
- Size: 1.58 MB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# π Mastering MERN Stack - Full-Stack Social Media Platform





**A production-ready social media platform demonstrating the complete MERN stack**
[Features](#-features) β’ [Quick Start](#-quick-start) β’ [Architecture](#-architecture) β’ [Development](#-development)
---
## π Table of Contents
- [Overview](#-overview)
- [Features](#-features)
- [Tech Stack](#-tech-stack)
- [Architecture](#-architecture)
- [Quick Start](#-quick-start)
- [Project Structure](#-project-structure)
- [Backend API](#-backend-api)
- [Frontend Application](#-frontend-application)
- [Development](#-development)
- [Testing](#-testing)
- [Deployment](#-deployment)
- [Contributing](#-contributing)
- [License](#-license)
---
## π Overview
**Mastering MERN** is a comprehensive social media platform built from scratch using the MERN stack (MongoDB, Express, React, Node.js). This project demonstrates **production-ready full-stack development** with modern best practices, authentication, real-time features, and responsive design.
### Why This Project?
- β
**Complete Full-Stack**: Backend API + Frontend SPA
- β
**Production Patterns**: Authentication, validation, error handling
- β
**Real-time Features**: Live updates, notifications, chat
- β
**Responsive Design**: Mobile-first UI with modern styling
- β
**Educational**: Clean code, comprehensive documentation
- β
**Scalable Architecture**: Modular design, separation of concerns
---
## β¨ Features
### User Features
- π **Authentication**: JWT-based auth with refresh tokens
- π€ **User Profiles**: Customizable profiles with avatars
- π **Posts**: Create, edit, delete posts with rich media
- π¬ **Comments**: Nested commenting system
- β€οΈ **Reactions**: Like, love, and react to posts
- π₯ **Social Graph**: Follow/unfollow users, friend requests
- π **Notifications**: Real-time notifications
- π¬ **Messaging**: Direct messaging between users
- π **Search**: Search users, posts, and hashtags
- π **Feed Algorithm**: Personalized content feed
### Technical Features
- π― **RESTful API**: Clean, documented REST endpoints
- π **Real-time Updates**: WebSocket integration
- πΎ **MongoDB**: NoSQL database with Mongoose ODM
- π **Security**: bcrypt passwords, JWT tokens, rate limiting
- π§ **Email Service**: Email verification and notifications
- πΌοΈ **File Upload**: Image/video uploads with Cloudinary
- π **Performance**: Redis caching, pagination, lazy loading
- π± **Responsive UI**: Works on desktop, tablet, and mobile
---
## π Tech Stack
### Backend
| Technology | Version | Purpose |
|------------|---------|---------|
| **Node.js** | 20.x | Runtime environment |
| **Express.js** | 4.18+ | Web framework |
| **MongoDB** | Latest | NoSQL database |
| **Mongoose** | 8.x | MongoDB ODM |
| **JWT** | 9.x | Authentication tokens |
| **bcryptjs** | 2.x | Password hashing |
| **Redis** | Latest | Caching and sessions |
| **Bull** | 4.x | Job queues |
| **Socket.io** | 4.x | Real-time communication |
### Frontend
| Technology | Version | Purpose |
|------------|---------|---------|
| **React** | 18.x | UI library |
| **Vite** | 5.x | Build tool |
| **TypeScript** | 5.x | Type safety |
| **React Router** | 6.x | Client-side routing |
| **Axios** | 1.x | HTTP client |
| **React Query** | 5.x | Server state management |
| **Zustand** | 4.x | Client state management |
| **Tailwind CSS** | 3.x | Utility-first CSS |
| **Shadcn/ui** | Latest | UI components |
### DevOps
- **Docker** & **Docker Compose** - Containerization
- **GitHub Actions** - CI/CD pipeline
- **ESLint** & **Prettier** - Code quality
---
## π Architecture
### High-Level System Architecture
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Frontend (React) β
β β
β ββββββββββββ ββββββββββββ βββββββββββββββββ β
β β Pages β βComponentsβ β State (Zustand)β β
β ββββββββββββ ββββββββββββ βββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββ β
β β React Query (Server State) β β
β ββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ
β HTTP/REST
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Backend API (Express) β
β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β Routes ββ βControllersβββ Services β β
β ββββββββββββ ββββββββββββ ββββββββββββ β
β β β
β ββββββββββββββββ΄ββββββββ β
β βΌ βΌ β
β ββββββββββββββ ββββββββββββββ β
β β MongoDB β β Redis β β
β β (Mongoose) β β (Cache) β β
β ββββββββββββββ ββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Backend Architecture (MVC Pattern)
```
backend/
βββ routes/ # Express route definitions
β βββ auth.routes.js
β βββ user.routes.js
β βββ post.routes.js
β
βββ controllers/ # Route handlers
β βββ auth.controller.js
β βββ user.controller.js
β βββ post.controller.js
β
βββ services/ # Business logic
β βββ auth.service.js
β βββ user.service.js
β βββ post.service.js
β
βββ models/ # Mongoose schemas
β βββ User.model.js
β βββ Post.model.js
β βββ Comment.model.js
β
βββ middleware/ # Express middleware
β βββ auth.middleware.js
β βββ validation.middleware.js
β βββ error.middleware.js
β
βββ utils/ # Helper functions
βββ email.util.js
βββ upload.util.js
βββ token.util.js
```
---
## π Quick Start
Get the platform running locally in **5 minutes**:
### Prerequisites
- **Node.js** >= 20.x
- **MongoDB** (local or Atlas)
- **Redis** (local or cloud)
- **Git**
### Installation
```bash
# 1. Clone the repository
git clone https://github.com/hassonor/mastering-mern.git
cd mastering-mern
# 2. Install backend dependencies
cd backend
npm install
# 3. Install frontend dependencies
cd ../frontend
npm install
# 4. Set up environment variables
cd ../backend
cp .env.example .env
# Edit .env with your configuration
# MongoDB (local)
MONGODB_URI=mongodb://localhost:27017/mern-social
# Redis (local)
REDIS_URL=redis://localhost:6379
# JWT
JWT_SECRET=your-super-secret-key
JWT_EXPIRES_IN=7d
# Email (optional - for production)
SENDGRID_API_KEY=your-sendgrid-key
SENDGRID_FROM_EMAIL=noreply@example.com
# Cloudinary (optional - for image uploads)
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
```
### Running Locally
#### Option 1: Manual Start
```bash
# Terminal 1 - Start MongoDB (if local)
mongod
# Terminal 2 - Start Redis (if local)
redis-server
# Terminal 3 - Start backend
cd backend
npm run dev
# Terminal 4 - Start frontend
cd frontend
npm run dev
```
#### Option 2: Docker Compose
```bash
# Start all services (MongoDB, Redis, Backend, Frontend)
docker-compose up
# Backend: http://localhost:5000
# Frontend: http://localhost:3000
```
### Access Points
| Service | URL | Description |
|---------|-----|-------------|
| **Frontend** | http://localhost:3000 | React application |
| **Backend API** | http://localhost:5000 | Express API |
| **API Docs** | http://localhost:5000/api-docs | Swagger documentation |
| **MongoDB** | mongodb://localhost:27017 | Database |
| **Redis** | redis://localhost:6379 | Cache |
---
## π Project Structure
```
mastering-mern/
βββ backend/ # Express backend
β βββ src/
β β βββ config/ # Configuration files
β β β βββ database.js # MongoDB connection
β β β βββ redis.js # Redis connection
β β β βββ cloudinary.js # File upload config
β β β
β β βββ models/ # Mongoose models
β β β βββ User.js
β β β βββ Post.js
β β β βββ Comment.js
β β β βββ Like.js
β β β βββ Notification.js
β β β
β β βββ routes/ # API routes
β β β βββ auth.routes.js
β β β βββ user.routes.js
β β β βββ post.routes.js
β β β βββ comment.routes.js
β β β
β β βββ controllers/ # Route controllers
β β βββ services/ # Business logic
β β βββ middleware/ # Express middleware
β β βββ utils/ # Helper functions
β β βββ validators/ # Request validation
β β βββ app.js # Express app setup
β β
β βββ tests/ # Backend tests
β βββ package.json
β βββ .env.example
β
βββ frontend/ # React frontend
β βββ src/
β β βββ components/ # Reusable components
β β β βββ common/ # Buttons, inputs, etc.
β β β βββ layout/ # Navbar, sidebar, footer
β β β βββ post/ # Post card, create post
β β β βββ user/ # User card, profile
β β β
β β βββ pages/ # Route pages
β β β βββ Home.tsx
β β β βββ Profile.tsx
β β β βββ Login.tsx
β β β βββ Register.tsx
β β β
β β βββ hooks/ # Custom React hooks
β β β βββ useAuth.ts
β β β βββ usePosts.ts
β β β βββ useInfiniteScroll.ts
β β β
β β βββ store/ # Zustand stores
β β β βββ authStore.ts
β β β βββ uiStore.ts
β β β
β β βββ api/ # API client
β β β βββ axios.ts # Axios instance
β β β βββ auth.api.ts
β β β βββ posts.api.ts
β β β
β β βββ types/ # TypeScript types
β β βββ utils/ # Helper functions
β β βββ App.tsx
β β βββ main.tsx
β β
β βββ package.json
β βββ vite.config.ts
β
βββ .github/
β βββ workflows/ # CI/CD pipelines
β βββ ci.yml
β
βββ docker-compose.yml # Docker services
βββ README.md
```
---
## π§ Backend API
### Key Endpoints
#### Authentication
```bash
POST /api/auth/register # Register new user
POST /api/auth/login # Login user
POST /api/auth/refresh # Refresh access token
GET /api/auth/me # Get current user
POST /api/auth/logout # Logout user
```
#### Users
```bash
GET /api/users # Get all users (paginated)
GET /api/users/:id # Get user by ID
PUT /api/users/:id # Update user profile
DELETE /api/users/:id # Delete user
POST /api/users/:id/follow # Follow user
DELETE /api/users/:id/follow # Unfollow user
```
#### Posts
```bash
GET /api/posts # Get feed (paginated)
POST /api/posts # Create post
GET /api/posts/:id # Get post by ID
PUT /api/posts/:id # Update post
DELETE /api/posts/:id # Delete post
POST /api/posts/:id/like # Like post
DELETE /api/posts/:id/like # Unlike post
```
#### Comments
```bash
GET /api/posts/:postId/comments # Get comments
POST /api/posts/:postId/comments # Add comment
PUT /api/comments/:id # Update comment
DELETE /api/comments/:id # Delete comment
```
---
## π» Frontend Application
### Key Features
#### Authentication Flow
```tsx
// Login component with form validation
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useAuthStore } from '@/store/authStore';
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(6)
});
function Login() {
const login = useAuthStore(state => state.login);
const { register, handleSubmit, formState: { errors } } = useForm({
resolver: zodResolver(loginSchema)
});
const onSubmit = async (data) => {
await login(data.email, data.password);
};
return ...;
}
```
#### Data Fetching with React Query
```tsx
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getPosts, createPost } from '@/api/posts.api';
function Feed() {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery({
queryKey: ['posts'],
queryFn: getPosts
});
const createMutation = useMutation({
mutationFn: createPost,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['posts'] });
}
});
return
...;
}
```
---
## π§ͺ Testing
### Backend Tests
```bash
# Run backend tests
cd backend
npm test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage
```
### Frontend Tests
```bash
# Run frontend tests
cd frontend
npm test
# E2E tests (Playwright)
npm run test:e2e
```
---
## π’ Deployment
### Backend Deployment (Railway/Render)
```bash
# Build for production
npm run build
# Start production server
npm start
```
### Frontend Deployment (Vercel/Netlify)
```bash
# Build for production
npm run build
# Preview build locally
npm run preview
```
### Docker Deployment
```bash
# Build and run all services
docker-compose up --build -d
# View logs
docker-compose logs -f
# Stop services
docker-compose down
```
---
## π€ Contributing
Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
---
## π License
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
---
**Made with β€οΈ by [Or Hasson](https://github.com/hassonor)**
β Star this repo if you're learning the MERN stack!