How to create a Node.js proxy hosted with Firebase cloud features?

I have an application that uses a YouTube API key to search for YouTube videos and display them on my page. I just found out that he is bad enough to expose all secrets for a client. So, the solution I'm looking at is for the client to send requests to the Firebase cloud function instead. The cloud function will serve as a proxy where my API key will be stored, not stored in the client.

How do I set it up?

First, I tried registering the object request

, but I get a cryptic error message.

error: SUPERVISOR clientError { Error: Parse Error bytesParsed: 0, code: 'HPE_INVALID_METHOD' } connecting=false, _hadError=false, bytesRead=193, , fd=
-1, reading=true, $ref=$, onread=function onread(nread, buffer) {

      

Here's the request GET

sent by the client who threw the error message above

https://localhost:5000/jpls-youtube-viewer/us-central1/helloWorld?part=snippet&type=video&q=Linkin+Park

      

Here's the repo of my app: https://github.com/jpls93/jpls-youtube-viewer

And here's the hosted site: https://jpls-youtube-viewer.firebaseapp.com/

+3


source to share


1 answer


I solved it by pointing the client request to my Firebase database url, after which I had the Firebase database url to request the YouTube REST API url and allow the response to my client. I had a problem with CORS, but that was just fixed by allowing access control / methods



exports.helloWorld = functions.https.onRequest((request, response) => {
  var term = request.query.q;
  // See https://howtofirebase.com/firebase-cloud-functions-753935e80323
  // why we're requiring it inside the function
  var YT_URL = "https://www.googleapis.com/youtube/v3/search";
  const axios = require("axios");
  axios
    .get(YT_URL, {
      params: {
        part: "snippet",
        type: "video",
        key: require("./secret"),
        q: term
      }
    })
    .then(YouTubeData => {
      response.set("Access-Control-Allow-Origin", "*");
      response.set("Access-Control-Allow-Methods", "GET, POST");
      response.status(200).send(YouTubeData.data.items);
    })
    .catch(err => console.error(err));
});

      

0


source







All Articles