0
0
FirebaseHow-ToBeginner · 3 min read

How to Use Firebase Hosting with Functions Easily

To use Firebase Hosting with Cloud Functions, deploy your functions and configure firebase.json to rewrite specific URLs to your functions. This setup lets Hosting serve your static files and forward API requests to your backend functions seamlessly.
📐

Syntax

The main parts to connect Firebase Hosting with Functions are:

  • firebase.json: Config file where you define rewrites from Hosting URLs to Functions.
  • functions/index.js: Your Cloud Functions code.
  • firebase deploy: Command to deploy both Hosting and Functions.

In firebase.json, use the rewrites array inside hosting to forward requests to a function by name.

json
{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      }
    ]
  }
}
💻

Example

This example shows how to serve static files from Hosting and forward all /api/** requests to a Cloud Function named api.

javascript and json
// functions/index.js
const functions = require('firebase-functions');
const express = require('express');
const app = express();

app.get('/hello', (req, res) => {
  res.send('Hello from Firebase Functions!');
});

exports.api = functions.https.onRequest(app);

// firebase.json
{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      }
    ]
  }
}
Output
When you visit /api/hello, you get: Hello from Firebase Functions!
⚠️

Common Pitfalls

Common mistakes include:

  • Not defining rewrites in firebase.json, so Hosting does not forward requests to functions.
  • Using the wrong function name in rewrites.
  • Not deploying both Hosting and Functions together.
  • Forgetting to initialize your function with functions.https.onRequest.

Always check your function names and rewrite paths carefully.

json
Wrong rewrite example:
{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "/api/**",
        "function": "wrongName"
      }
    ]
  }
}

Correct rewrite example:
{
  "hosting": {
    "public": "public",
    "rewrites": [
      {
        "source": "/api/**",
        "function": "api"
      }
    ]
  }
}
📊

Quick Reference

Summary tips for using Firebase Hosting with Functions:

  • Define your functions in functions/index.js using functions.https.onRequest.
  • Set up firebase.json rewrites to forward URLs to your functions.
  • Deploy with firebase deploy to update both Hosting and Functions.
  • Test your URLs to confirm Hosting serves static files and functions respond correctly.

Key Takeaways

Use rewrites in firebase.json to connect Hosting URLs to Cloud Functions.
Deploy both Hosting and Functions together with firebase deploy.
Name your functions correctly and match them in rewrites.
Functions must use functions.https.onRequest to handle HTTP requests.
Test your setup by visiting Hosting URLs that trigger your functions.