Serve dynamic content and host microservices with Cloud Functions Stay organized with collections Save and categorize content based on your preferences.
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
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.
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:
InitializeCloud Functions by running the following command fromthe root of your project directory:
firebase init functions
When prompted, select JavaScript (this walk-through example uses JS).
Check that you have a
functionsdirectory in your local projectdirectory (created by the Firebase command you just ran). Thisfunctionsdirectory is where the code forCloud Functions lives.
Step 2: Create and test an HTTPS function for yourHosting site
Open
/functions/index.jsin your favorite editor.Replace the file's contents with the following code.
This code creates an HTTPS function (named
bigben) that replies to HTTPSrequests with aBONGfor 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>`);});Test your functions locally using theFirebase Local Emulator Suite.
From the root of your local project directory, run the followingcommand:
firebase emulators:start
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.
Open your
firebase.jsonfile.Add the following
rewriteconfiguration under thehostingsection:"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)}}]}Confirm that your redirect works as expected by testing again with theFirebase emulators.
From the root of your local project directory, run the followingcommand:
firebase emulators:start
Visit the locally hosted URL for your site as returned by the CLI(usually
localhost:5000), but append the URL withbigben, like so:http://localhost:5000/bigben
Iterate on your function and its functionality for your site. Use theFirebase emulators to test these iterations.
Howregion works within thefunction block
If
regionis omitted from afunctionblock 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 requiresregionto be specified in thehosting.rewritesconfig.
HowpinTag works within thefunction block
The
pinTagfeature 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
Note: If you add a"pinTag": trueto afunctionblock of thehosting.rewritesconfig, then the "pinned" function will be deployed along with your staticHosting resources and configuration, even when running. If you roll back aversion of your site, the "pinned" function is also rolled back.firebase deploy --only hosting pinTagto 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-west1us-central1us-east1europe-west1asia-east1
504 (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.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
Access your live site and your function at the following URLs:
Your Firebase subdomains:
PROJECT_ID.web.app/bigbenandPROJECT_ID.firebaseapp.com/bigbenAny connectedcustom domains:
CUSTOM_DOMAIN/bigben
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.
Install Express.js in your local project by running the following commandfrom your
functionsdirectory:npm install express --save
Open your
/functions/index.jsfile, then import and initialize Express.js:constfunctions=require('firebase-functions/v1');constexpress=require('express');constapp=express();
Add the following two endpoints:
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>`);});And another endpoint to return the
BONGcount 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)});});
Export the Express.js app as an HTTPS function:
exports.app=functions.https.onRequest(app);
In your
firebase.jsonfile, direct all requests to theappfunction.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" } ] }}
public 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.
Install the
corsmiddleware by running the following command:npm install --save cors
Open your
/functions/index.jsfile, then addcorsto 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
Set up caching for your dynamic content on aglobal CDN.
Interact with other Firebase services using theFirebase Admin SDK.
Review thepricing and thequotas and limits forCloud Functions.
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.