कंसोल पर जाएं

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 (run npm install -g firebase-tools).

    • You have initialized Firebase Hosting.

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

  2. If you've already set up Cloud Functions, you can proceed to Step 2: Create an HTTP function.

  3. If you've not already 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. Make sure that you have a functions directory in your local project directory. This functions directory is where the code for Cloud Functions lives.

Step 2: Create an HTTP function to 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 HTTP function (named bigben) that replies to HTTP requests with a BONG for each hour of the day, just like a clock.

    const functions = require('firebase-functions');
    
    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. Deploy this function to your site by running the following command from the root of your project directory:

    firebase deploy

    The function is now reachable at the URL
    https://us-central1-projectID.cloudfunctions.net/bigben.

Visit the Cloud Functions documentation to learn more about HTTP requests.

The next step walks you through how to access this HTTP function from a Firebase Hosting URL so that it can generate dynamic content for your Firebase-hosted site.

Step 3: Direct hosting requests to your function

With rewrite rules, you can direct requests that match specific patterns to a single destination. For example, to direct all requests from the page /bigben on your Hosting site to execute the bigben function.

  1. Open your firebase.json file.

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

    "hosting": {
     // ...
    
     // Add the "rewrites" attribute within "hosting"
     "rewrites": [ {
       "source": "/bigben",
       "function": "bigben"
     } ]
    }
    
  3. Run the firebase deploy command again.

    Your function is now reachable via the following URLs:

    • Your Firebase subdomains: projectID.web.app/bigben and projectID.firebaseapp.com/bigben

    • Any connected custom domains: custom-domain/bigben

Visit the Hosting configuration page for more details about rewrite rules. You can also learn about the priority order of responses for various Hosting configurations.

Use a web framework

You can use web frameworks, like Express.js, in Cloud Functions to serve your app's dynamic content and write complex web apps more easily.

The following section provides a walk-through example for using Express.js with Firebase Hosting and Cloud Functions.

  1. Install Express.js in your local project by running the following command from your functions directory:

    npm install express --save
  2. Open your /functions/index.js file, then import and initialize Express.js:

    const functions = require('firebase-functions');
    const express = require('express');
    const app = express();
    
  3. Add the following two endpoints:

    1. Add the first endpoint to serve the index of our website at /.

      app.get('/', (req, res) => {
        const date = new Date();
        const hours = (date.getHours() % 12) + 1;  // London is UTC + 1hr;
        res.send(`
          <!doctype html>
          <head>
            <title>Time</title>
            <link rel="stylesheet" href="/style.css">
            <script src="/script.js"></script>
          </head>
          <body>
            <p>In London, the clock strikes:
              <span id="bongs">${'BONG '.repeat(hours)}</span></p>
            <button onClick="refresh(this)">Refresh</button>
          </body>
        </html>`);
      });
      
    2. And another endpoint to return the BONG count as an API, in JSON format, under /api:

      app.get('/api', (req, res) => {
        const date = new Date();
        const hours = (date.getHours() % 12) + 1;  // London is UTC + 1hr;
        res.json({bongs: 'BONG '.repeat(hours)});
      });
      
  4. Export the Express.js app as an HTTP function:

    exports.app = functions.https.onRequest(app);
    
  5. In your firebase.json file, direct all requests to the app function. This rewrite allows Express.js to serve the different subpath that we configured (in this example, / and /api).

    {
     "hosting": {
       // ...
    
       // Add the "rewrites" attribute within "hosting"
       "rewrites": [ {
         "source": "**",
         "function": "app"
       } ]
     }
    }
    

Add middleware

Continuing our example, now that you're using Express.js, you can add Express.js middleware in the typical way. For example, you can enable CORS requests on our endpoints.

  1. Install the cors middleware by running the following command:

    npm install --save cors
  2. Open your /functions/index.js file, then add cors to your Express.js app, like so:

    const cors = require('cors')({origin: true});
    app.use(cors);
    

Visit the Cloud Functions documentation to learn more about using Firebase with Express apps and middleware modules.

Test locally

You can serve and run your HTTP functions locally using the Firebase CLI. This allows you to view and test your Firebase project before deploying to production.

  1. Make sure that both the Firebase CLI and the firebase-functions SDK are the latest versions available. To update both, run the following two commands from the functions directory of your local project:

    npm install -g firebase-tools
    npm install --save firebase-functions@latest
  2. Serve your Firebase project locally by running the following command from the root of your project directory.

    This command emulates hosting and functions on locally hosted URLs.

    firebase serve
When you're using Cloud Functions to generate dynamic content for Firebase Hosting, firebase serve, by default, uses your local HTTP functions as proxies for hosting. For more configuration options for Firebase Hosting and Cloud Functions, refer to the Firebase CLI Reference.

Next steps