Ken
Ken

Reputation: 212

Fetch API-key protected data with Firebase Cloud Function

I have a (fictitious) web application that gets data from the YouTube Data API, using my API key. With my current Python-based server, I can just use Python requests. With "serverless" hosted Firebase, I can't expose my API key client-side, so I must use a Cloud Function (I guess).

I want the user to visit https://example.com/videos/[id] and get some API-key protected data in real time.

If I didn't need to hide the API key, I could simply import/require the YouTube API and grab the data. But here I need to invoke the cloud function when the page loads and get the data into the page and I don't know how to do that.

So far, all I can think of is: when the user visits the page, we add a node somewhere with the video ID. A Function listens on that node for any new children, fetches the data and saves it to a node that my page is listening on where it then appears. That seems complicated...

Upvotes: 1

Views: 496

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

No you don't necessary need to "add some (database) nodes" for (#1) the triggering of the Cloud Function, and (#2) the "transmission" of the result to the client.

You can use a Callable Cloud Function, which is directly called from your app and which directly sends back to your app some data that can be JSON encoded (for example the result of the call to the YouTube API done by the Cloud Function or any other JSON that you would generate from the YouTube API response).


You could also use a "simple" HTTPs Cloud Function which, to summarize, is similar to a REST API endpoint.

The main differences between the Callable Cloud Functions and the HTTPs Cloud Functions are:

  • The way you call them: For an HTTPs CF you need to issue an HTTP request, for a Callable you use the dedicated method from the Client SDK for your platform.
  • With callables, Firebase Authentication and FCM tokens, when available, are automatically included in requests.
  • The functions.https.onCall trigger automatically deserializes the request body and validates auth tokens.

Upvotes: 4

Codex
Codex

Reputation: 1281

I think still you can expose your Youtube API key and add some restrictions to it in your project for,

  1. Domain (*.something.com)
  2. Service restriction (use this key for only youtube data enter image description here)

As @renaud pointed out, you can use http functions in firebase to abstract all these process and its fairly quick(I am doing something similar and response is always in ms).

Upvotes: 2

Related Questions