Serve dynamic content and host microservices with Cloud Functions

PairCloud Functions withFirebase Hosting to generate and serve yourdynamic content or build REST APIs as microservices.

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

For example use cases and samples forCloud Functions integrated withFirebase Hosting, visit ourserverless overview.

ConnectCloud Functions toFirebase Hosting

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

Note that to improve the performance of serving dynamic content, you canoptionally tune yourcache settings.

Step 1: Set upCloud Functions

  1. Make sure that you have the latest version of theFirebase CLI and thatyou've initializedFirebase Hosting.

    For detailed instructions about installing the CLI and initializingHosting, see theGet Started guide forHosting.

  2. Make sure that you've set upCloud Functions:

    • If you'vealready set upCloud Functions, you can proceed toStep 2: Create and test an HTTPS function.

    • If you'venot set upCloud Functions:

      1. InitializeCloud Functions by running the following command fromthe root of your project directory:

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

      3. Check that you have afunctions directory in your local projectdirectory (created by the Firebase command you just ran). Thisfunctions directory is where the code forCloud Functions lives.

Step 2: Create and test an HTTPS function for yourHosting 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 (namedbigben) that replies to HTTPSrequests with aBONG for each hour of the day, just like a clock.

    constfunctions=require('firebase-functions/v1');exports.bigben=functions.https.onRequest((req,res)=>{consthours=(newDate().getHours()%12)+1//LondonisUTC+1hr;res.status(200).send(`<!doctypehtml><head><title>Time</title></head><body>${'BONG '.repeat(hours)}</body></html>`);});
  3. Test your functions locally using theFirebase Local Emulator Suite.

    1. From the root of your local project directory, run the followingcommand:

      firebase emulators:start
    2. Access the function via the local URL returned by the CLI, forexample:http://localhost:5001/PROJECT_ID/us-central1/bigben.

Visit theCloud Functions documentationto learn more about HTTPS requests.

The next step walks you through how to access this HTTPS functionfrom aFirebase Hosting URL so that it can generate dynamic content for yourFirebase-hosted site.

Step 3: Direct HTTPS requests to your function

Withrewrite rules, you can direct requeststhat match specific patterns to a single destination. The following steps showyou how to direct all requests from the path../bigben on yourHostingsite to execute thebigben function.

  1. Open yourfirebase.json file.

  2. Add the followingrewrite configuration under thehosting 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 theFirebase emulators.

    1. From the root of your local project directory, run the followingcommand:

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

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

Howregion works within thefunction block

Ifregion is omitted from afunction block of thehosting.rewritesconfig, theFirebase CLI attempts to automatically detect the region fromthe function's source code which, if unspecified, defaults tous-central1.If the function's source code is unavailable, the CLI attempts to detectthe region from the deployed function. If the function is in multiple regions,the CLI requiresregion to be specified in thehosting.rewritesconfig.

HowpinTag works within thefunction block

ThepinTag feature is only available inCloud Functions for Firebase (2nd gen).With this feature, you can ensure that each function for generating yoursite's dynamic content is kept in sync with your staticHosting resourcesandHosting config. Also, this feature allows you to preview your rewritesto functions onHosting preview channels.

If you add"pinTag": true to afunction block of thehosting.rewritesconfig, then the "pinned" function will be deployed along with your staticHosting resources and configuration, even when runningfirebase deploy --only hosting. If you roll back aversion of your site, the "pinned" function is also rolled back.

Note: If you add apinTag to anexisting rewrite, you must first deploythe updated rewrite to your "live" channel. After that deploy, you can thenpreview changes to your function's code inHosting preview channelswithout affecting production.

This feature relies onCloud Run tags,which have a limit of 1000 tags per service and 2000 tags per region. Thismeans that after hundreds of deploys, the oldest versions of a site may stopworking.

For the best performance, colocate your functions withHosting bychoosing one of the following regions:

  • us-west1
  • us-central1
  • us-east1
  • europe-west1
  • asia-east1
Note:Firebase Hosting is subject to a 60-second request timeout. Even ifyou configure your HTTPS function with a longer request timeout, you'll stillreceive an HTTPS status code504 (request timeout) if your function requiresmore than 60 seconds to run. To support dynamic content that requires longercompute time, consider using anApp Engine flexible environment.

Visit theHosting configuration page formore details about rewrite rules. You canalso learn about thepriority order of responsesfor variousHosting configurations.

Note that to improve the performance of serving dynamic content, you canoptionally tune yourcache settings.

Step 4: Deploy your function

Once your function is working as desired in the emulator, you can proceed todeploying, testing, and running it withreal project resources. This is agood time to consider setting runtime options tocontrol scaling behaviorfor functions running in production.

Note: To deploy to a runtime environment of Node.js 10 and higher, yourFirebase project must be on theBlaze pricing plan. For moredetails, refer toCloud Functions pricing.
  1. Deploy your function as well as yourHosting content and config to yoursite by running the following command from the root of your local projectdirectory:

    firebase deploy --only functions,hosting
  2. Access your live site and your function at the following URLs:

    • Your Firebase subdomains:
      PROJECT_ID.web.app/bigben andPROJECT_ID.firebaseapp.com/bigben

    • Any connectedcustom domains:
      CUSTOM_DOMAIN/bigben

Caution: New HTTP and HTTP callable functions deployed with anyFirebase CLIlower than version 7.7.0 are private by default and throw HTTP 403 errors wheninvoked. Either explicitlymake these functions publicorupdate yourFirebase CLI before you deployany new functions.

Use a web framework

You can use web frameworks, likeExpress.js, inCloud Functions toserve your app's dynamic content and write complex web apps more easily.

Firebase Hosting also supports HTTPS requests toCloud Run containers. Learn more about this serverless, highly scalable service in theHosting paired withCloud Run documentation.

The following section provides a walk-through example for using Express.js withFirebase Hosting andCloud Functions.

  1. Install Express.js in your local project by running the following commandfrom yourfunctions directory:

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

    constfunctions=require('firebase-functions/v1');constexpress=require('express');constapp=express();
  3. Add the following two endpoints:

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

      Note: This walk-through example requires a couple of static files(script.js and style.css).
      app.get('/',(req,res)=>{constdate=newDate();consthours=(date.getHours()%12)+1;//LondonisUTC+1hr;res.send(`<!doctypehtml><head><title>Time</title><linkrel="stylesheet"href="/style.css"><scriptsrc="/script.js"></script></head><body><p>InLondon,theclockstrikes:<spanid="bongs">${'BONG '.repeat(hours)}</span></p><buttononClick="refresh(this)">Refresh</button></body></html>`);});
    2. And another endpoint to return theBONG count as an API, in JSONformat, under/api:

      app.get('/api',(req,res)=>{constdate=newDate();consthours=(date.getHours()%12)+1;//LondonisUTC+1hr;res.json({bongs:'BONG '.repeat(hours)});});
  4. Export the Express.js app as an HTTPS function:

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

    { "hosting": {   // ...   // Add the "rewrites" attribute within "hosting"   "rewrites": [ {     "source": "**",     "function": "app"   } ] }}
Note: The static files in thepublic directory takeprecedence over the rewrites, so any static files will be served alongside theCloud Functions endpoints.

Add middleware

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

  1. Install thecors middleware by running the following command:

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

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

Visit theCloud Functions documentationto learn more about using Firebase with Express apps and middleware modules.

Next steps

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-05 UTC.