Firebase Cloud Functions are fantastic, but the URL that you get to run them isn’t so nice. You’ll get given a URL that looks like the following when you create some cloud functions:
https://us-central1-demoapp.cloudfunctions.net/functionName
If you are wanting to use Firebase to build an API for your application for example (like I wanted to), then you would probably prefer your URL looks like this:
https://myapp.com/functionName
Fortunately, you can. The only downside is you have to use Firebase hosting if you want to be able to alias your functions to your name. If you’re self-hosting your own site somewhere else and using Firebase, then you can’t alias cloud functions.
To alias cloud functions, open up your firebase.json
file and inside of the hosting
and rewrites
section add in your rule. My example showcases an API endpoint which gets sent to a Firebase cloud function called api
which handles the request.
{ "database": { "rules": "database.rules.json" }, "hosting": { "public": "public", "rewrites": [ { "source":"/api/**", "function":"api" }, { "source": "**", "destination": "/index.html" } ] } }
In my instance, I have a single page application so I have created a wildcard rewrite to send all requests to the index.html
file so my Javascript framework can take over.
All you have to remember is source
and function
where source
is your URL pattern (which supports wildcards and matchers) and function
is the name of your created function inside of functions/index.js
.
I highly recommend installing and using Express to handle your routing needs inside of cloud functions if you’re wanting to work with aliases, especially for Firebase driven API’s.
In a future article I’ll show you how you can create an API using Firebase and alias the functions.