How To Upload a YouTube Video With NodeJS ?
Hello everyone, today I'm going to tell you how to upload a video to youtube using a nodejs application.
First, we will need to create an project in google cloud console here, after you create your project, open your project and in the left sidebar, find APIs & Services - Credentials tab and open credentials tab. The link for this should be at: https://console.cloud.google.com/apis/credentials?project={{your-project-name}}
Click CREATE CREDENTIALS and then a select OAuth Client ID. Select web application and add authorized javascript origin and redirect URI. You can use http://localhost:3000 or whatever port you want for local development. After you set the redirect uri and authorized javascript origins, click create. Download the json file of credentials.
Alright, now the fun part begins. Now we are going to create a node js application which will handle authorization of the google account, and then the upload after authorization redirect. For this, we are going to create a http server. Here is a breakdown of what this http server will be responsible for.
-
Import the libraries and credentials from the json and prepare scopes for auth.
-
Use these credentials and scopes to create an authorization url.
-
Redirect from the app to authorization url.
-
Handle the redirect url for the authorization. If authorized, set the authorized credentials to oauth client.
-
Upload the video using the authorized client.
Let's go step by step.
- Create an npm project with npm init After you download your client_secret json file, place it into your npm project. Also add 'googleapis' library to your project with this command
npm i -d googleapis
Now let's import the json data and create the authorization url
const http = require("http");
const url = require("url");
const { google } = require("googleapis");
const fs = require("fs");
const { web: credentials } = require("./client_secret.json");
const oauth2Client = new google.auth.OAuth2(
credentials.client_id,
credentials.client_secret,
"http://localhost:3000" // this is our redirect url for the authorization.
);
// This is the required scope for the youtube upload.
const scopes = ["https://www.googleapis.com/auth/youtube.upload"];
- Create authorization url
const authorizationUrl = oauth2Client.generateAuthUrl({
access_type: "online",
scope: scopes,
include_granted_scopes: true,
});
- Now let's create our http server and redirect to the authorization url.
http.createServer(async function (req, res) {
if (req.url == "/") {
res.writeHead(301, { Location: authorizationUrl });
res.end();
}
})
- Now the application will redirect to authorization url and google authorization flow will be running on the website. After you approve the requested permissions in the website, it's going to redirect back to our application with a code to get access token. The redirect url will look like this: http://localhost:3000?code=12Sfv3121312blablabla...
What we need to do now is, we should check if we have the code and if we have it, we should make a request to oauth with code to get access token. Add this piece of code inside httpServer after the first part
if (req.url.includes("code")) {
let q = url.parse(req.url, true).query;
if (q.error) {
console.log("Error:" + q.error);
} else {
let { tokens } = await oauth2Client.getToken(q.code);
oauth2Client.setCredentials(tokens);
userCredential = tokens;
}
}
- Now that we have our access token, we can actually upload our video right after we create our userCredential. Just paste the code right after "userCredential = tokens;" line
const service = google.youtube({
version: "v3",
});
service.videos.insert({
auth: oauth2Client,
part: "snippet,status",
requestBody: {
snippet: {
title: "My video title",
description: "My video description",
tags: "tag1,tag2,tag3",
// https://gist.github.com/dgp/1b24bf2961521bd75d6c
categoryId: 1,
defaultLanguage: "en",
defaultAudioLanguage: "en",
},
status: {
privacyStatus: "private",
},
},
media: {
body: fs.createReadStream("video.mp4"),
},
}, function (err, response) {
if (err) {
console.log("The API returned an error: " + err);
return;
}
// Video is uploaded
}
);
Here is a gist of the whole file to make it easier for you to implement. I hope this writing helps you.