Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-pro· GoogleHugging Face LMArena Human Preference 140K

write a code for youtube clone

  1. User

    write a code for youtube clone

  2. Gemini Assistant

    Of course. Building a full YouTube clone is a massive project, but I can provide you with the code for a simplified, functional Mini-YouTube clone that covers the absolute core features:

    • Uploading a video with a title.
    • Listing all uploaded videos on a homepage.
    • Watching a selected video on its own page.

    This example uses a popular and relatively simple stack: Node.js, Express for the backend, EJS for templating (HTML), and Multer for handling file uploads.


    Prerequisites

    You must have Node.js installed on your computer. This will also install npm (Node Package Manager).


    Step 1: Set Up Your Project

    1. Create a new folder for your project called youtube-clone.

    2. Open a terminal or command prompt inside that folder.

    3. Run npm init -y to create a package.json file.

    4. Run npm install express ejs multer to install the necessary libraries.

    5. Create the following folder structure inside youtube-clone:

      youtube-clone/
      ├── node_modules/
      ├── public/
      │   └── css/
      │       └── style.css
      ├── views/
      │   ├── index.ejs
      │   ├── upload.ejs
      │   └── watch.ejs
      ├── uploads/          <-- Multer will create and store videos here
      ├── package.json
      └── server.js         <-- Our main application file
      

    Step 2: The Code

    Here is the code for each file. Just copy and paste it into the correct files you created above.

    server.js (The Backend Logic)

    This is the heart of your application. It handles routing, file uploads, and rendering the pages.

    const express = require('express');
    const multer = require('multer');
    const path = require('path');
    
    const app = express();
    const port = 3000;
    
    // In-memory "database" to store video metadata
    // In a real app, you would use a database like MongoDB or PostgreSQL
    let videos = [];
    let idCounter = 0;
    
    // --- Multer Configuration for File Uploads ---
    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, 'uploads/'); // Store videos in the 'uploads' directory
        },
        filename: (req, file, cb) => {
            // Create a unique filename to prevent overwriting
            cb(null, Date.now() + path.extname(file.originalname));
        }
    });
    
    const upload = multer({ 
        storage: storage,
        limits: { fileSize: 100000000 }, // Limit file size (e.g., 100MB)
        fileFilter: (req, file, cb) => {
            // Allow only video files
            const filetypes = /jpeg|jpg|png|mp4|mkv|mov/;
            const mimetype = filetypes.test(file.mimetype);
            const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
            
            if (mimetype && extname) {
                return cb(null, true);
            }
            cb("Error: File upload only supports the following filetypes - " + filetypes);
        }
    }).single('video'); // 'video' is the name of the input field in our form
    
    
    // --- Middleware ---
    app.set('view engine', 'ejs'); // Set EJS as the templating engine
    app.use(express.static('public')); // Serve static files from the 'public' directory
    app.use('/uploads', express.static('uploads')); // Make the 'uploads' directory accessible
    
    // Middleware to parse form data
    app.use(express.urlencoded({ extended: true }));
    
    
    // --- Routes ---
    
    // GET / - Homepage: Display a list of all uploaded videos
    app.get('/', (req, res) => {
        res.render('index', { videos: videos });
    });
    
    // GET /upload - Display the upload form
    app.get('/upload', (req, res) => {
        res.render('upload');
    });
    
    // POST /upload - Handle the video upload
    app.post('/upload', (req, res) => {
        upload(req, res, (err) => {
            if (err) {
                res.send(err);
            } else {
                if (req.file == undefined) {
                    res.send('Error: No File Selected!');
                } else {
                    // Add video metadata to our "database"
                    const newVideo = {
                        id: idCounter++,
                        title: req.body.title,
                        description: req.body.description,
                        filename: req.file.filename,
                    };
                    videos.push(newVideo);
                    res.redirect('/');
                }
            }
        });
    });
    
    // GET /watch/:id - Watch a specific video
    app.get('/watch/:id', (req, res) => {
        const videoId = parseInt(req.params.id, 10);
        const video = videos.find(v => v.id === videoId);
    
        if (!video) {
            return res.status(404).send('Video not found.');
        }
    
        res.render('watch', { video: video });
    });
    
    
    // --- Start the Server ---
    app.listen(port, () => {
        console.log(`Server started on http://localhost:${port}`);
    });
    

    views/index.ejs (Homepage)

    This page lists all the videos.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>MiniTube - Home</title>
        <link rel="stylesheet" href="/css/style.css">
    </head>
    <body>
        <header>
            <h1>MiniTube</h1>
            <a href="/upload" class="button">Upload Video</a>
        </header>
        <main>
            <h2>Latest Videos</h2>
            <div class="video-grid">
                <% if(videos.length > 0) { %>
                    <% videos.forEach(video => { %>
                        <a href="/watch/<%= video.id %>" class="video-card">
                            <div class="thumbnail">
                                <!-- In a real app, you'd generate a thumbnail -->
                                <video width="100%">
                                    <source src="/uploads/<%= video.filename %>#t=2" type="video/mp4">
                                </video>
                            </div>
                            <h3><%= video.title %></h3>
                        </a>
                    <% }) %>
                <% } else { %>
                    <p>No videos uploaded yet. Be the first!</p>
                <% } %>
            </div>
        </main>
    </body>
    </html>
    

    views/upload.ejs (Upload Page)

    A simple form to upload a video file and its title.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Upload Video - MiniTube</title>
        <link rel="stylesheet" href="/css/style.css">
    </head>
    <body>
        <header>
            <h1><a href="/">MiniTube</a> > Upload</h1>
        </header>
        <main>
            <form action="/upload" method="POST" enctype="multipart/form-data" class="upload-form">
                <div class="form-group">
                    <label for="title">Video Title</label>
                    <input type="text" id="title" name="title" required>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea id="description" name="description" rows="4"></textarea>
                </div>
                <div class="form-group">
                    <label for="video">Video File</label>
                    <input type="file" id="video" name="video" accept="video/*" required>
                </div>
                <button type="submit" class="button">Upload</button>
            </form>
        </main>
    </body>
    </html>
    

    views/watch.ejs (Watch Page)

    This page displays the video player.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><%= video.title %> - MiniTube</title>
        <link rel="stylesheet" href="/css/style.css">
    </head>
    <body>
        <header>
            <h1><a href="/">MiniTube</a></h1>
        </header>
        <main class="watch-page">
            <video controls autoplay class="video-player">
                <source src="/uploads/<%= video.filename %>" type="video/mp4">
                Your browser does not support the video tag.
            </video>
            <div class="video-details">
                <h2><%= video.title %></h2>
                <p><%= video.description %></p>
            </div>
        </main>
    </body>
    </html>
    

    public/css/style.css (Basic Styling)

    This makes the site look decent.

    body {
        font-family: Arial, sans-serif;
        margin: 0;
        background-color: #f4f4f4;
        color: #333;
    }
    
    header {
        background-color: #ff0000;
        color: white;
        padding: 1rem 2rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    header h1 a, header a {
        color: white;
        text-decoration: none;
    }
    
    main {
        padding: 2rem;
        max-width: 1200px;
        margin: auto;
    }
    
    .button {
        background-color: #c00;
        color: white;
        padding: 0.5rem 1rem;
        border-radius: 4px;
        text-decoration: none;
        border: none;
        cursor: pointer;
    }
    
    .video-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 1.5rem;
    }
    
    .video-card {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        text-decoration: none;
        color: #333;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        transition: transform 0.2s;
    }
    
    .video-card:hover {
        transform: translateY(-5px);
    }
    
    .video-card .thumbnail {
        width: 100%;
        height: 150px;
        background-color: #000;
    }
    
    .video-card video {
        object-fit: cover;
        height: 100%;
        width: 100%;
    }
    
    .video-card h3 {
        padding: 0.5rem 1rem;
        margin: 0;
        font-size: 1rem;
    }
    
    /* Watch Page */
    .watch-page .video-player {
        width: 100%;
        max-width: 900px;
        display: block;
        margin: 0 auto;
        background-color: #000;
    }
    
    .watch-page .video-details {
        margin-top: 1rem;
        background: white;
        padding: 1.5rem;
        border-radius: 8px;
    }
    
    /* Upload Form */
    .upload-form .form-group {
        margin-bottom: 1rem;
    }
    
    .upload-form label {
        display: block;
        margin-bottom: 0.5rem;
    }
    
    .upload-form input[type="text"],
    .upload-form textarea,
    .upload-form input[type="file"] {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-sizing: border-box;
    }
    
    .upload-form button {
        width: 100%;
        padding: 0.75rem;
        font-size: 1.1rem;
    }
    

    Step 3: Run the Application

    1. Make sure you are in the youtube-clone directory in your terminal.
    2. Run the command: node server.js
    3. You should see the message: Server started on http://localhost:3000
    4. Open your web browser and go to http://localhost:3000.

    You can now upload videos, see them on the homepage, and click to watch them!

    Important Limitations and Next Steps

    This is a very basic MVP. A real-world YouTube has immense complexity. Here's what you'd need to add to make it more robust:

    1. Real Database: The videos array is temporary and will be lost every time you restart the server. You would use MongoDB (NoSQL) or PostgreSQL (SQL) to store video metadata permanently.
    2. User Accounts: Implement user sign-up, login, and channels (using libraries like Passport.js).
    3. Video Transcoding: When a video is uploaded, it should be processed into multiple resolutions (1080p, 720p, 480p) and formats for different devices and network speeds. The industry-standard tool for this is FFmpeg. This is a computationally intensive process.
    4. Cloud Storage: Storing video files on your server's local disk is not scalable. You would use a service like Amazon S3 or Google Cloud Storage.
    5. CDN (Content Delivery Network): To serve videos quickly to users worldwide, you would use a CDN like AWS CloudFront or Cloudflare.
    6. Thumbnail Generation: Automatically create a thumbnail image from the video using FFmpeg.
    7. More Features: Comments, likes/dislikes, subscriptions, search, a recommendation algorithm, etc.