Shorten Firebase Storage Download URLs with Cloud Functions

Cloud Functions is a new feature in Firebase that enables us to run a backend code in response to a triggering event. Triggering events can be a Firebase feature such as a new/updated entry in database or uploaded/deleted file in the storage or a HTTPS request.

So the elements in Cloud Functions are;

  • a Triggering Event
  • a Listening Function
  • a Response Function

Once you deploy the code, it will listen for the triggering event and then call the function after triggered. One important point is the function should be a Promise as we will see shortly.

In this article, we will create a function that shortens file urls that Firebase Storage generates.

File URLs that Firebase Storage generates are pretty long to share. To shorten the file URLs, we will use Google URL Shortener API. Here is the URL shortening process;

  1. File uploaded by a user
  2. File URL written to the database
  3. Event triggers the URL Shortener function
  4. Function shortens the long URL and push new short URL to the database

Let’s begin to code;

As mentioned earlier, we need to return a promise inside a Cloud Function. Since Google URL Shortener is based on HTTPS request, we need to use ‘request-promise’ which is a HTTP request client with Promise support.

We succesfully set the environment for using the Cloud Functions. Let’s start listening to triggering event. Triggering event will be a new entry in the database.

The following code will wait for a new entry under: user/user1/files/file1/downloadURL, then it will call a function .

And here is the function to shorten the original file download URL

Full example is available here.