Simplifying YouTube Video Downloads: Building a Chrome Extension with JavaScript and Node.js and Express — Part 1
Introduction
As a content creator or someone working on editing projects, the need for video and audio resources is inevitable. YouTube stands as an immense reservoir of valuable content, but downloading videos can be a repetitive task, especially when dealing with multiple videos regularly. In this tutorial, we’ll embark on a journey to simplify YouTube video downloads by creating a Chrome extension that automates the process. We’ll utilize Node.js to build the backend functionality for our extension.
Why a Chrome Extension?
While various websites offer YouTube video downloads, creating a personalized solution allows for a seamless and efficient experience. The Chrome extension we’re building will eliminate the need to copy and paste video URLs on a separate website, streamlining the download process with just a few clicks.
In this tutorial, we’ll walk through the process of creating a simple YouTube video downloader using Node.js, Express, and the ytdl-core library. This first part of the project will enable users to download YouTube videos by providing the video URL and desired quality.
Disclaimer
Downloading videos from YouTube is against the YouTube Policy. The only videos that your allowed to download is your own which you can already do using YouTube Studio.
Prerequisites:
Before we start, make sure you have Node.js installed on your machine. You can download it from Node.js official website
Step 1: Set Up the Project
1. Create a new project directory.
mkdir youtube-downloader
cd youtube-downloader
2. Initialize a new Node.js project.
npm init -y
Step 2: Setup the Frontend
- Create a file named
index.html
and set up your UI. You can clean it up to make it look attractive but for this tutorial, function over beauty.
<!-- HTML Document Structure -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Document Metadata -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page Title -->
<title>Youtube Downloader</title>
</head>
<body>
<!-- Input and Selection Elements -->
<p>Enter your URL Below:</p>
<input type="url" name="URLBox" id="URLBox">
<br>
<select name="quality_option" id="quality_option" required>
<!-- Quality Options -->
<option value="" selected>None</option>
<option value="highest">mp4 1080p</option>
<option value="lowestvideo">mp4 360p</option>
<option value="highest">webm 1080p</option>
<option value="highest">mp4 720p</option>
<option value="highest">webm 720p</option>
<option value="lowest">mp4 480p</option>
<option value="lowest">mp4 360p</option>
<option value="highestaudio">mp4 </option>
</select>
<!-- Download Button -->
<button type="button" id="download_Btn" onclick="download()">Download</button>
<!-- Placeholder for Testing -->
<p id="test"></p>
<!-- Script Inclusion -->
<script src="script.js"></script>
</body>
</html>
2. Create a file named script.js
and set up the functionality of the button to communicate with our server.
// Selecting HTML elements by their IDs
let test = document.getElementById("test");
let URL = document.getElementById("URLBox");
let download_Btn = document.getElementById("download_Btn");
let quality = document.getElementById("quality_option");
// Function to execute when the download button is clicked
function download() {
// Displaying the entered URL in the 'test' paragraph
test.innerHTML = `URL: ${URL.value}`;
// Sending URL and quality to the server
send_URL_to_Server(URL.value, quality.value);
}
// to send a GET request to the server
function send_URL_to_Server(URL, quality) {
// Constructing the server URL with query parameters
window.location.href = `http://localhost:8080/download?URL=${URL}&quality=${quality}`;
}
Step 3: Create the Server
First we must make a new directory name server
that will contain our server files and install the required dependencies: `express`, `cors`, and `ytdl-core`.
mkdir server
cd server
npm install express cors ytdl-core
Create a file named `index.js` and set up the Express server.
// index.js
// Importing required modules
const express = require('express');
const cors = require('cors');
const ytdl = require('ytdl-core');
// Creating an instance of Express
const app = express();
const PORT = 8080;
// Using CORS middleware to enable cross-origin resource sharing
app.use(cors());
// Setting up a route to handle GET requests at '/download'
app.get('/download', (req, res) => {
// Implementation will go here
});
// Instantiating a server to listen on port 8080
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- The code starts by importing necessary modules —
express
for creating a web server,cors
for handling Cross-Origin Resource Sharing, andytdl-core
for downloading YouTube videos. - An instance of the Express application is created using
const app = express();
. - The
app.use(cors());
line adds CORS middleware to the Express app, allowing cross-origin requests. app.listen(8080, ...)
starts the server on port 8080, and a message is logged to the console once the server is running.
Step 4: Handle YouTube Video Download
Inside the `/download` route, handle the YouTube video download using the `ytdl-core` library.
app.get('/download', (req, res) => {
// Extracting query parameters from the request
const URL = req.query.URL;
const quality = req.query.quality;
// Setting the response header to trigger a file download with specified file name
res.header('Content-Disposition', 'attachment; filename="video.mp4"');
// Using ytdl-core to download a YouTube video based on the provided URL and quality
ytdl(URL, { quality: quality }).pipe(res);
});
- The
app.get('/download',...)
sets up a route to handle GET requests at the/download
path. The callback function extracts query parameters (URL
andquality
) from the request. res.header('Content-Disposition', 'attachment; filename="video.mp4"');
sets the response header to trigger a file download with the specified filename.- The
ytdl
module is used to download a YouTube video based on the provided URL and quality. The downloaded video is piped directly to the response (res
), allowing for streaming the video to the client.
Step 4: Run the Server
Run your Node.js server to start listening for requests.
node index.js
Step 5: Test the YouTube Video Downloader
Run your html code on a live server and test the code in your browser.
or
You can test the server code directly by manually entering http://localhost:8080/download?URL=YOUR_YOUTUBE_URL&quality=YOUR_QUALITY in your browser. Replace `YOUR_YOUTUBE_URL` with the YouTube video URL and `YOUR_QUALITY` with the desired quality (e.g., “highest” for the highest available quality).
Conclusion
Congratulations! You’ve successfully built a YouTube video downloader using Node.js, Express, and ytdl-core. Users can now download YouTube videos by providing the video URL and specifying the desired quality. Feel free to customize and enhance the project by including a functionality to detect and display what video you are downloading and also display how much data it would take to download.
ytdl-core
ytdl-core is a versatile Node.js module designed for downloading YouTube videos. Created by the developer known as fent, this module offers a range of powerful features. One notable function is ytdl.validateURL
, providing functionality to validate YouTube URL’s. This module proves invaluable for various applications, and its flexibility allows for diverse use cases.
Feel free to follow and support the creator of the blog post that I referenced a lot in making this project — Moorad
-If you have any questions or thoughts, tell me in the comments-