Serve dynamic content and host microservices with Cloud Functions  |  Firebase Hosting

Serve dynamic content and host microservices with Cloud Functions

Pair Cloud Functions with Firebase Hosting to generate and serve your dynamic content or build REST APIs as microservices.

Cloud Functions for Firebase lets you automatically run backend code in response to HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.

For example use cases and samples for Cloud Functions integrated with Firebase Hosting, visit our serverless overview.

Connect Cloud Functions to Firebase Hosting

This section provides a walk-through example for connecting a function to Firebase Hosting.

Note that to improve the performance of serving dynamic content, you can optionally tune your cache settings.

Step 1: Set up Cloud Functions

  1. Make sure that you have the latest version of the Firebase CLI and that you've initialized Firebase Hosting.

For detailed instructions about installing the CLI and initializing Hosting, see the Get Started guide for Hosting.

  1. Make sure that you've set up Cloud Functions:
    • If you've already set up Cloud Functions, you can proceed to Step 2: Create and test an HTTPS function.
    • If you've not set up Cloud Functions:
      1. Initialize Cloud Functions by running the following command from the root of your project directory:

        firebase init functions
        
      2. When prompted, select JavaScript (this walk-through example uses JS).

      3. Check that you have a functions directory in your local project directory (created by the Firebase command you just ran). This functions directory is where the code for Cloud Functions lives.

Step 2: Create and test an HTTPS function for your Hosting site

  1. Open /functions/index.js in your favorite editor.

  2. Replace the file's contents with the following code. This code creates an HTTPS function (named bigben) that replies to HTTPS requests with a BONG for each hour of the day, just like a clock.

    const functions = require('firebase-functions/v1');
    

exports.bigben = functions.https.onRequest((req, res) => { const hours = (new Date().getHours() % 12) + 1 // London is UTC + 1hr; res.status(200).send(<!doctype html> <head> <title>Time</title> </head> <body> ${'BONG '.repeat(hours)} </body> </html>); });

3. Test your functions locally using the [Firebase Local Emulator Suite](/content/docs/emulator-suite/index.html).
1. From the root of your local project directory, run the following command:

   ```
   firebase emulators:start
   ```

2. Access the function via the local URL returned by the CLI, for example:
   `http://localhost:5001/PROJECT_ID/us-central1/bigben`.

Visit the [Cloud Functions documentation](/content/docs/functions/http-events/index.html) to learn more about HTTPS requests.

The next step walks you through how to access this HTTPS function _from a_ _Firebase Hosting URL_ so that it can generate dynamic content for your Firebase-hosted site.

### **Step 3:** Direct HTTPS requests to your function

With [rewrite rules](/content/docs/hosting/full-config#rewrites/index.html), you can direct requests that match specific patterns to a single destination. The following steps show you how to direct all requests from the path `../bigben` on your Hosting site to execute the `bigben` function.

1. Open your [`firebase.json` file](/content/docs/cli#the_firebasejson_file/index.html).

2. Add the following `rewrite` configuration under the `hosting` section:

"hosting": { // ...

// Add the "rewrites" attribute within "hosting" "rewrites": [ { "source": "/bigben", "function": { "functionId": "bigben", "region": "us-central1" // optional (see note below) "pinTag": true // optional (see note below) } } ] }


3. Confirm that your redirect works as expected by testing again with the Firebase emulators.
1. From the root of your local project directory, run the following command:

   ```
   firebase emulators:start
   ```
2. Visit the locally hosted URL for your site as returned by the CLI (usually `localhost:5000`), but append the URL with `bigben`, like so:
   `http://localhost:5000/bigben`

4. Iterate on your function and its functionality for your site. Use the Firebase emulators to test these iterations.

**How `region` works within the `function` block**

> If `region` is omitted from a `function` block of the `hosting.rewrites` config, the Firebase CLI attempts to automatically detect the region from the function's source code which, if unspecified, defaults to `us-central1`. If the function's source code is unavailable, the CLI attempts to detect the region from the deployed function. If the function is in multiple regions, the CLI requires `region` to be specified in the `hosting.rewrites` config.

**How `pinTag` works within the `function` block**

> The `pinTag` feature is only available in Cloud Functions for Firebase (2nd gen). With this feature, you can ensure that each function for generating your site's dynamic content is kept in sync with your static Hosting resources and Hosting config. Also, this feature allows you to preview your rewrites to functions on Hosting preview channels.
> If you add `