I have a web application through which I'd like to be able create playlists, add videos to a playlist, delete a video etc, to my youtube channel. I have created a service account and downloaded the service account credentials key file and set up my OAuth 2.0 Client IDs in the Google Developer Console.
To authenticate my app, I followed the instructions in the README.md
for the google-api-nodejs-client
here https://github.com/googleapis/google-api-nodejs-client - under service account credentials
Here is my controller file...
I should note that the project uses ES Modules and thus "type": "module"
is set in package.json
. This is why you'l notice for example that I am importing __dirname
as a utility since ES Modules do not support the regular __dirname
.
import googleapi from "googleapis";
const { google } = googleapi;
import Auth from "@google-cloud/local-auth";
const { authenticate } = Auth;
import path from "path";
import __dirname from "../utils/dirname.js";
async function initialize() {
try {
const auth = await authenticate({
keyfilePath: path.join(__dirname, "../service_account_credentials.json"),
scopes: ["https://www.googleapis.com/auth/youtube"],
});
console.log("Auth details");
console.log(auth);
google.options({ auth });
} catch (e) {
console.log(e);
}
}
initialize();
const oauth2Client = new google.auth.OAuth2(
"YOUR_CLIENT_ID",
"YOUR_CLIENT_SECRET",
"http://localhost:5000/oauth2callback"
);
// initialize the Youtube API library
const youtube = google.youtube({ version: "v3", auth: oauth2Client });
class YoutubeController {
static async createPlaylist(req, res) {
const { name } = req.body;
const playlist = await youtube.playlists.insert({
part: "snippet,status",
resource: {
snippet: {
title: name,
description: `${name} videos.`,
},
status: {
privacyStatus: "private",
},
},
});
res.json(playlist);
}
}
The initialize
function, is the one that throws the error and I can't quite figure it out. I think because of that, when I make a POST
request to the route that calls the method createPlaylist
inside the class, I get back No access, refresh token or API key is set.
I've been going through the docs trying to understand how everything flows but I'm a little stuck.
A similar question was asked here - TypeError: Cannot read property 'redirect_uris' of undefined but there are no answers and the suggested workflow does not work for my case so I'd really appreciate your help on this.