Mapping custom domains to cloud functions



This is one of a series of articles about Going serverless with Firebase. You many want to read about Firebase cloud functions and Custom domains and ssl with Firebase hosting before this article.

Redirecting requests to your custom domain

Now that you've set up your custom domain as described in Custom domains and ssl with Firebase hosting and created some cloud functions as in Firebase cloud functions you'll want to publish the end point for those functions, so for example

https://efxapi.com/v2

directs to the express app that's being hosted in a cloud function. This is defined in the firebase.json file used when you deploy files to firebase hosting. In this example, as well as cloud functions there is also the Ephemeral Exchange console and dashboard as well as the JavaScript client API cdn 
<script src="https://efxapi.com/scripts/effex-api-client-v2.2.min.js"></script>

The files deployed to firebase hosting look like this, in addition to the deployed functions.
 

Firebase.json

The objective is to divert any api requests (which all start with /v2) to the cloud function, and everything else to either static files or a special 404 page for not found. As with all things firebase, this is simple using "rewrites"

{
  "hosting": {
    "public": "public",

    // the api directs here
   "rewrites": [ {
      "source": "/v2/**", 
      "function": "api"
    } ]
    
    // static files will pick up directly
    
  }
}

This is redirecting request to any urls starting with /v2 to the cloud function called api and everything else will attempt to use a static hosted file.  The index.js for the deployed functions contains this line
// function http entry point for function
exports.api = functions.https.onRequest(efxapiv2.app);

which exposes the function api to match the rewrite in the firebase.json configuration file. 



For other articles on this topic see Going serverless with Firebase



Comments