Load Firebase SDKs from reserved URLs

Load Firebase SDKs from reserved URLs

Firebase Hosting reserves URLs in your site beginning with /__. This reserved namespace makes it easier to use other Firebase products together with Firebase Hosting.
These reserved URLs are available both when you deploy to Firebase (firebase deploy) or when you run your app on a local server (firebase serve).

Add scripts for reserved URLs


Because Firebase Hosting is served over HTTP/2 when deployed, you can boost performance by loading files from the same origin. Firebase Hosting serves all versions of the Firebase JavaScript SDK from special URLs formatted like so:

/__/firebase/js-sdk-version/firebase-sdk-name.js

We strongly recommend loading only the libraries that you use in your app. For example, to include only Authentication and Cloud Firestore, add the following scripts to the bottom of your <body> tag, but before you use any Firebase services:

<body>
  <!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
  <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="/__/firebase/6.4.0/firebase-app.js"></script>

  <!-- Add Firebase products that you want to use -->
  <script src="/__/firebase/6.4.0/firebase-auth.js"></script>
  <script src="/__/firebase/6.4.0/firebase-firestore.js"></script>
</body>

SDK auto-configuration


Automatic SDK configuration makes it easy to manage multiple environments (such as dev, staging, and production) from a single codebase. By relying on the reserved Hosting URL, you can deploy the same code to multiple Firebase projects.
In addition to hosting the SDKs themselves, the reserved namespace also provides all of the configuration necessary to initialize the SDK for the Firebase project associated with the Hosting site. This Firebase configuration and SDK initialization is provided by a script that you can include directly:

<!-- Load the Firebase SDKs before loading this file -->
<script src="/__/firebase/init.js"></script>

When you deploy to Firebase or test your app locally, this script automatically configures the Firebase JavaScript SDK for the active Firebase project and initializes the SDK.
If you prefer to control initialization yourself, the Firebase configuration values are also available in JSON form:

fetch('/__/firebase/init.json').then(async response => {
  firebase.initializeApp(await response.json());
});

Auth helpers


Firebase Authentication uses the reserved namespace to provide special JavaScript and HTML to complete authentication with providers via OAuth. This allows each Firebase project to have a unique Firebase subdomain, increasing the security of Firebase Authentication.
In addition, this allows you to use your own custom domain for the authDomain option of firebase.initializeApp(). If you configure a custom domain for Firebase Hosting, then you can also specify that custom domain (instead of your web.app or firebaseapp.com subdomain) when initializing the Firebase SDKs.

Reserved URLs and service workers


If you are building a Progressive Web App (PWA), you might create a service worker that has a "navigation fallback" and renders a specific URL by default if it doesn't match a list of precached items.










If you're using the sw-precache library, you can add a navigation fallback whitelist setting that excludes the reserved namespace:

{
  navigateFallbackWhitelist: [/^(?!\/__).*/]
}

In general, just remember that the double-underscore namespace is reserved for Firebase usage and that you should not intercept these requests in your service worker.


Serve dynamic content and host microservices using Firebase Hosting

Firebase Hosting integrates with serverless computing options, including Cloud Functions for Firebase and Cloud Run. Using Firebase Hosting with these options, you can host microservices by directing HTTP requests to trigger your functions and containerized apps to run in a managed, secure environment.
Cloud Functions for Firebase: You write and deploy a function, which is backend code that responds to a specific trigger. Then, using Firebase Hosting, you can direct HTTPS requests to trigger your function to run.
Cloud Run: You write and deploy an application packaged in a container image. Then, using Firebase Hosting, you can direct HTTPS requests to trigger your containerized app to run.

Use cases


How can you use serverless computing options with Firebase Hosting?
  • Serve dynamic content — In addition to serving static content on your Hosting site, you can serve dynamically generated responses from a function or containerized app that is performing server-side logic.
    For example, you can point a URL pattern (like /blog/<blog-post-id>) to a function that uses the URL's blog post ID parameter to retrieve content dynamically from your database.
  • Build REST APIs — You can create a microservice API using functions.
    For instance, functions can handle the sign-in functionality for your website. While your website is hosted at /, any request to /api is redirected to your microservice API. For an example, check out this open-source sample.
  • Cache dynamic content — You can configure caching of your dynamic content on a global CDN.
    For example, if a function generates new content only periodically, you can speed up your app by caching the generated content for at least a short period of time. You can also potentially reduce execution costs because the content is served from the CDN rather than via a triggered function or containerized app.
  • Prerender your single-page apps — You can improve SEO and optimize sharing across various social networks by creating dynamic meta tags. To learn more, watch this video or check out this open-source sample.

Choosing a serverless option


While both Cloud Functions for Firebase and Cloud Run integrate with Firebase Hosting and offer a fully managed, autoscaling, and secure serverless environment, the two options can be leveraged for different use cases and desired level of customized configuration.








The following table describes some basic considerations for using Cloud Functions for Firebase versus Cloud Run. For a full listing of quotas, limits, and metrics, refer to each product's detailed documentation (Cloud Functions for Firebase or Cloud Run).
ConsiderationCloud Functions for FirebaseCloud Run
SetupThe Firebase CLI bundles multiple tasks into single commands, from initializing to building and deploying.Containers offer more customizable options, so setup, build, and deployment tasks involve discrete steps.
Runtime environmentRequires Node.js, but you can specify which versionof Node to use (currently, Node version 6 or 8).When building your container, you specify the runtime environment.
Language and frameworks support
JavaScript and TypeScript
Web frameworks, like Express.js, are supported.
Any language that Dockerfiles support, includingGo, Node.js, Python, Java, and others
Web frameworks for each language are supported.
Timeout for Hosting request60 seconds (see Note below)60 seconds (see Note below)
Concurrency1 request per function instance
(no concurrency per instance)
80 concurrent requests per container instance
BillingCloud Functions usage
Free usage quota, and no billing account is required
Cloud Run usage + Container Registry storage
Free usage quota, but a billing account is required











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 ourserverless 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 functionsdirectory 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 andprojectID.firebaseapp.com/bigben
    • Any connected custom domainscustom-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



Serve dynamic content and host microservices with Cloud Run







Pair Cloud Run with Firebase Hosting to generate and serve your dynamic content or build REST APIs as microservices.
Using Cloud Run, you can deploy an application packaged in a container image. Then, using Firebase Hosting, you can direct HTTPS requests to trigger your containerized app.
  • Cloud Run supports several languages (including Go, Node.js, Python, and Java), giving you the flexibility to use the programming language and framework of your choice.
  • Cloud Run automatically and horizontally scales your container image to handle the received requests, then scales down when demand decreases.
  • You only pay for the CPU, memory, and networking consumed during request handling.
For example use cases and samples for Cloud Run integrated with Firebase Hosting, visit our serverless overview.

This guide shows you how to:
  1. Write a simple Hello World application
  2. Containerize an app and upload it to Container Registry
  3. Deploy the container image to Cloud Run
  4. Direct Hosting requests to your containerized app
Note that to improve the performance of serving dynamic content, you can optionally tune your cache settings.

Before you begin


Before using Cloud Run, you need to complete some initial tasks, including setting up a billing account, enabling the Cloud Run API, and installing the gcloud command line tool.

Set up billing for your project


Cloud Run does offer free usage quota, but you still must have a billing account associated with your Firebase project to use or try out Cloud Run.





Enable the API and install the SDK


  1. Enable the Cloud Run API in the Google APIs console:
    1. Open the Cloud Run API page in the Google APIs console.
    2. When prompted, select your Firebase project.
    3. Click Enable on the Cloud Run API page.
  2. Install and initialize the Cloud SDK.

Install the gcloud beta component


  1. Run the following command to install the gcloud beta component:
    gcloud components install beta
  2. Update components:
    gcloud components update
  3. Check that the gcloud tool is configured for the correct project:
    gcloud config list

Step 1: Write the sample application


Note that Cloud Run supports many other languages in addition to the languages shown in the following sample.





  1. Create a new directory named helloworld-go, then change directory into it:
    mkdir helloworld-go
    cd helloworld-go
  2. Create a new file named helloworld.go, then add the following code:

    package main
    
    import (
            "fmt"
            "log"
            "net/http"
            "os"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
            log.Print("Hello world received a request.")
            target := os.Getenv("TARGET")
            if target == "" {
                    target = "World"
            }
            fmt.Fprintf(w, "Hello %s!\n", target)
    }
    
    func main() {
            log.Print("Hello world sample started.")
    
            http.HandleFunc("/", handler)
    
            port := os.Getenv("PORT")
            if port == "" {
                    port = "8080"
            }
    
            log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
    }
    
    This code creates a basic web server that listens on the port defined by the PORT environment variable.
Your app is finished and ready to be containerized and uploaded to Container Registry.

Step 2: Containerize an app and upload it to Container Registry


  1. Containerize the sample app by creating a new file named Dockerfile in the same directory as the source files. Copy the following content into your file.

    # Use the offical Golang image to create a build artifact.
    # This is based on Debian and sets the GOPATH to /go.
    # https://hub.docker.com/_/golang
    FROM golang as builder
    
    # Copy local code to the container image.
    WORKDIR /go/src/github.com/knative/docs/helloworld
    COPY . .
    
    # Build the outyet command inside the container.
    # (You may fetch or manage dependencies here,
    # either manually or with a tool like "godep".)
    RUN CGO_ENABLED=0 GOOS=linux go build -v -o helloworld
    
    # Use a Docker multi-stage build to create a lean production image.
    # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
    FROM alpine
    
    # Copy the binary to the production image from the builder stage.
    COPY --from=builder /go/src/github.com/knative/docs/helloworld/helloworld /helloworld
    
    # Service must listen to $PORT environment variable.
    # This default value facilitates local development.
    ENV PORT 8080
    
    # Run the web service on container startup.
    CMD ["/helloworld"]
    
  2. Build your container image using Cloud Build by running the following command from the directory containing your Dockerfile:
    gcloud builds submit --tag gcr.io/projectID/helloworld
    Upon success, you will see a SUCCESS message containing the image name
    (gcr.io/projectID/helloworld).
The container image is now stored in Container Registry and can be re-used if desired.
Note that, instead of Cloud Build, you can use a locally installed version of Docker to build your container locally.

Step 3: Deploy the container image to Cloud Run


  1. Deploy using the following command:
    gcloud beta run deploy --image gcr.io/projectID/helloworld
  2. When prompted:
  3. Wait a few moments for the deploy to complete. On success, the command line displays the service URL. For example:
    https://helloworld-random_hash-us-central1.a.run.app
  4. Visit your deployed container by opening the service URL in a web browser.
The next step walks you through how to access this containerized app from a Firebase Hosting URL so that it can generate dynamic content for your Firebase-hosted site.

Step 4: Direct hosting requests to your containerized app


With rewrite rules, you can direct requests that match specific patterns to a single destination.
The following example shows how to direct all requests from the page /helloworld on your Hosting site to trigger the startup and running of your helloworld container instance.
  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. Open your firebase.json file.
  3. Add the following rewrite configuration under the hosting section:
    "hosting": {
      // ...
    
      // Add the "rewrites" attribute within "hosting"
      "rewrites": [ {
        "source": "**",
        "run": {
          "serviceId": "helloworld",  // "service name" (from when you deployed the container image)
          "region": "us-central1"     // optional (if omitted, default is us-central1)
        }
      } ]
    }
    
  4. Deploy your hosting configuration to your site by running the following command from the root of your project directory:
    firebase deploy
Your container is now reachable via the following URLs:
  • Your Firebase subdomains: projectID.web.app/helloworld andprojectID.firebaseapp.com/helloworld
  • Any connected custom domainscustom-domain/helloworld






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.

Test locally


During development, you can run and test your container image locally. For detailed instructions, visit the Cloud Run documentation.

Next steps


Manage cache bahavior

Firebase Hosting uses a powerful global CDN to make your site as fast as possible.
Any requested static content is automatically cached on the CDN. If you redeploy your site's content, Firebase Hosting automatically clears all your cached static content across the CDN until the next request.
However, because Cloud Functions and Cloud Run services generate content dynamically, the content for a given URL can vary based on such things as user input or the user's identity. To account for this, requests that are handled by backend code do not cache on the CDN by default.
You can, though, configure caching behavior for dynamic content. For example, if a function generates new content only periodically, you can speed up your app by caching the generated content for at least a short period of time.
You can also potentially reduce function execution costs because the content is served from the CDN rather than via a triggered function. Read more about optimizing function execution and services in the Cloud Functions and Cloud Run documentation.
Learn more about caching behavior in Google's web developer documentation.

Set Cache-Control


The main tool that you use to manage cache for dynamic content is the Cache-Control header. By configuring this header, you can communicate both to the browser and the CDN how long your content can be cached. In your function, you set Cache-Control like so:

res.set('Cache-Control', 'public, max-age=300, s-maxage=600');

In this example header, the directives do three things:
  • public — Marks the cache as public. This means that both the browser and the intermediate servers (meaning the CDN for Firebase Hosting) can cache the content.
  • max-age — Tells the browser and the CDN how many seconds that they can cache the content. When the set time expires, the browser and the CDN must revalidate the content with the origin server. In the example header, we're allowing the browser and the CDN to cache the content for five minutes (see s-maxage below for specific controls for CDN caching).
  • s-maxage — Overrides the max-age directive for the CDN-caching only; tells the CDN how many seconds that it can cache the content. When the set time expires, the CDN must revalidate the content with the origin server. In the example header, we're overriding the setting for max-age for the CDN only and allowing the CDN to cache the content for ten minutes.
For max-age and s-maxage, set their values to the longest amount of time that you're comfortable with users receiving stale content. If a page changes every few seconds, use a small time value. However, other types of content can be safely cached for hours, days, or even months.
You can learn more about the Cache-Control header on the Mozilla Developer Network and in Google'sweb developer documentation.

When is cached content served?


The browser and the CDN cache your content based on:
  • The hostname
  • The path
  • The query string
  • The content of the request headers specified in the Vary header

Vary headers


The Vary header determines which request headers should be used to provide an appropriate response (whether the cached content is valid or if the content should be revalidated with the origin server).
Most of the time, you don't need to worry about the Vary header. Firebase Hosting automatically sets an appropriate Vary header on your response for common situations. This includes making sure that any session cookie or authorization header that you're using is made part of the cache key, which prevents accidental leaks of content.
In some advanced use cases, you might have other headers that you need to affect the cache. When that's the case, you can simply set the Vary header on your response:

res.set('Vary', 'Accept-Encoding, X-My-Custom-Header');

With these settings, two otherwise identical requests with different X-My-Custom-Header headers are cached separately.




Using cookies


When using Firebase Hosting together with Cloud Functions or Cloud Run, cookies are generally stripped from incoming requests. This is necessary to allow for efficient CDN cache behavior. Only the specially-named __session cookie is permitted to pass through to the execution of your app.
When present, the __session cookie is automatically made a part of the cache key, meaning that it's impossible for two users with different cookies to receive the other's cached response. Only use the __session cookie if your app serves different content depending on user authorization.




Deploy to your site using the Hosting REST API

The Firebase Hosting REST API enables programmatic and customizable deployments to your Firebase-hosted sites. Use this REST API to deploy new or updated hosting configurations and content files.
As an alternative to using the Firebase command line interface (CLI) for deployments, you can use the Firebase Hosting REST API to programmatically create a new version of assets for your site, upload files to the version, then deploy the version to your site.
For example, with the Firebase Hosting REST API, you can:
  • Schedule deploys. By using the REST API in conjunction with a cron job, you can change Firebase-hosted content on a regular schedule (for example, to deploy a special holiday or event-related version of your content).
  • Integrate with developer tools. You can create an option in your tool to deploy your web app projects to Firebase Hosting using just one click (for example, clicking a deploy button within an IDE).
  • Automate deploys when static content is generated. When a process generates static content programmatically (for example, user-generated content such as a wiki or a news article), you can deploy the generated content as static files rather than serving them dynamically. This saves you expensive compute power and serves your files in a more scalable way.
This guide first describes how to enable, authenticate, and authorize the API. Then this guide walks through an example to create a Firebase Hosting version, to upload required files to the version, then finally to deploy the version.
You can also learn more about this REST API in the full Hosting REST API reference documentation.

Before you begin: Enable the REST API


You must enable the Firebase Hosting REST API in the Google APIs console:
  1. Open the Firebase Hosting API page in the Google APIs console.
  2. When prompted, select your Firebase project.
  3. Click Enable on the Firebase Hosting API page.

Step 1: Get an access token to authenticate and authorize API requests


Firebase projects support Google service accounts, which you can use to call Firebase server APIs from your app server or trusted environment. If you're developing code locally or deploying your application on-premises, you can use credentials obtained via this service account to authorize server requests.
To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.
To generate a private key file for your service account:
  1. In the Firebase console, open Settings > Service Accounts.
  2. Click Generate New Private Key, then confirm by clicking Generate Key.
  3. Securely store the JSON file containing the key.
Use your Firebase credentials together with the Google API Client Library for your preferred language to retrieve a short-lived OAuth 2.0 access token:

const {google} = require('googleapis');
function getAccessToken() {
  return new Promise(function(resolve, reject) {
    var key = require('./service-account.json');
    var jwtClient = new google.auth.JWT(
      key.client_email,
      null,
      key.private_key,
      SCOPES,
      null
    );
    jwtClient.authorize(function(err, tokens) {
      if (err) {
        reject(err);
        return;
      }
      resolve(tokens.access_token);
    });
  });
}

After your access token expires, the token refresh method is called automatically to retrieve an updated access token.

Step 2: Create a new version for your site


Your first API call is to create a new Version for your site. Later in this guide, you’ll upload files to this version, then deploy it to your site.
  1. Determine the site-name of the site to which you want to deploy.
  2. Call the versions.create endpoint using your site-name in the call.
    (Optional) You can also pass a Firebase Hosting configuration object in the call, including setting a header that caches all files for a specified length of time.
    For example:
    curl -H "Content-Type: application/json" \
           -H "Authorization: Bearer access-token" \
           -d '{
                 "config": {
                   "headers": [{
                     "glob": "**",
                     "headers": {
                       "Cache-Control": "max-age=1800"
                     }
                   }]
                 }
               }' \
    https://firebasehosting.googleapis.com/v1beta1/sites/site-name/versions
    
This API call to versions.create returns the following JSON:

{
  "name": "sites/site-name/versions/version-id",
  "status": "CREATED",
  "config": {
    "headers": [{
      "glob": "**",
      "headers": {
        "Cache-Control": "max-age=1800"
      }
    }]
  }
}

This response contains a unique identifier for the new version, in the format: sites/site-name/versions/version-id. You’ll need this unique identifier throughout this guide to reference this specific version.

Step 3: Specify the list of files you want to deploy


Now that you have your new version identifier, you need to tell Firebase Hosting which files you want to eventually deploy in this new version.


This API requires that you identify files by a SHA256 hash. So, before you can make the API call, you’ll first need to calculate a hash for each static file by Gzipping the files then taking the SHA256 hash of each newly compressed file.
For this example, let's say that you want to deploy three files in the new version: file1file2, and file3.
  1. Gzip the files:
    gzip file1 && gzip file2 && gzip file3
    You now have three compressed files file1.gzfile2.gz, and file3.gz.
  2. Get the SHA256 hash of each compressed file:
    cat file1.gz | openssl dgst -sha256
    
    66d61f86bb684d0e35f94461c1f9cf4f07a4bb3407bfbd80e518bd44368ff8f4
    
    cat file2.gz | openssl dgst -sha256
    
    490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083
    
    cat file3.gz | openssl dgst -sha256
    
    59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315
    
    You now have the three SHA256 hashes of the three compressed files.
  3. Send these three hashes in an API request to the versions.populateFiles endpoint. List each hash by the desired path for the uploaded file (in this example, /file1/file2, and /file3).
    For example:
    $ curl -H "Content-Type: application/json" \
             -H "Authorization: Bearer access-token" \
             -d '{
                   "files": {
                     "/file1": "66d61f86bb684d0e35f94461c1f9cf4f07a4bb3407bfbd80e518bd44368ff8f4",
                     "/file2": "490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083",
                     "/file3": "59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315"
                   }
                 }' \
    https://firebasehosting.googleapis.com/v1beta1/sites/site-name/versions/version-id:populateFiles
    
This API call to versions.populateFiles returns the following JSON:

{
  "uploadRequiredHashes": [
    "490423ebae5dcd6c2df695aea79f1f80555c62e535a2808c8115a6714863d083",
    "59cae17473d7dd339fe714f4c6c514ab4470757a4fe616dfdb4d81400addf315"
  ],
  "uploadUrl": "https://upload-firebasehosting.googleapis.com/upload/sites/site-name/versions/version-id/files"
}

This response includes:
  • The hash of each file that needs to be uploaded. For instance, in this example file1 had already been uploaded in a previous version, so its hash is not included in the uploadRequiredHashes list.
  • The uploadUrl which is specific to the new version.
In the next step to upload the two new files, you’ll need the hashes and the uploadURL from the versions.populateFiles response.

Step 4: Upload required files


You need to individually upload each required file (those files which are listed in uploadRequiredHashes from the versions.populateFiles response in the previous step). For these file uploads, you’ll need the file hashes and the uploadUrl from the previous step.
  1. Append a forward slash and the hash of the file to the uploadUrl to create a file-specific URL in the format: https://upload-firebasehosting.googleapis.com/upload/sites/site-name/versions/version-id/files/file-hash.
  2. Upload all the required files one-by-one (in this example, only file2.gz and file3.gz) to the file-specific URL using a series of requests.
    For example, to upload the compressed file2.gz:
    curl -H "Authorization: Bearer access-token" \
           -H "Content-Type: application/octet-stream" \
           --data-binary @./file2.gz \
    https://upload-firebasehosting.googleapis.com/upload/sites/site-name/versions/version-id/files/file-hash
    
Successful uploads return a 200 OK HTTP response.

Step 5: Update the status of the version to FINALIZED


After you’ve uploaded all the files which are listed in the versions.populateFiles response, you can update the status of your version to FINALIZED.
Call the versions.patch endpoint with the status field in your API request set to FINALIZED.
For example:

curl -H "Content-Type: application/json" \
       -H "Authorization: Bearer access-token" \
       -X PATCH \
       -d '{"status": "FINALIZED"}' \
https://firebasehosting.googleapis.com/v1beta1/sites/site-name/versions/version-id?update_mask=status

This API call to versions.patch returns the following JSON. Check that status has been updated to FINALIZED.

{
  "name": "sites/site-name/versions/version-id",
  "status": "FINALIZED",
  "config": {
    "headers": [{
      "glob": "**",
      "headers": {"Cache-Control": "max-age=1800"}
    }]
  },
  "createTime": "2018-12-02T13:41:56.905743Z",
  "createUser": {
    "email": "service-account-email@site-name.iam.gserviceaccount.com"
  },
  "finalizeTime": "2018-12-02T14:56:13.047423Z",
  "finalizeUser": {
    "email": "your-email@domain.tld"
  },
  "fileCount": "5",
  "versionBytes": "114951"
}

Step 6: Release the version for deployment


Now that you have a finalized version, release it for deployment. For this step, you need to create a Release of your version that contains the hosting configuration and all the content files for your new version.
Call the releases.create endpoint to create your release.
For example:

curl -H "Authorization: Bearer access-token" \
       -X POST
https://firebasehosting.googleapis.com/v1beta1/sites/site-name/releases?versionName=sites/site-name/versions/version-id

This API call to releases.create returns the following JSON:

{
  "name": "sites/site-name/releases/release-id",
  "version": {
    "name": "sites/site-name/versions/version-id",
    "status": "FINALIZED",
    "config": {
    "headers": [{
      "glob": "**",
      "headers": {"Cache-Control": "max-age=1800"}
    }]
  }
  },
  "type": "DEPLOY",
  "releaseTime": "2018-12-02T15:14:37Z"
}

The hosting configuration and all the files for the new version should now be deployed to your site, and you can access your files using the URLs:
  • https://site-name.web.app/file1
  • https://site-name.web.app/file2
  • https://site-name.web.app/file3
These files are also accessible on URLs associated with your site-name.firebaseapp.com domain.
You can also see your new release listed in the Firebase console on your Hosting page.




Cloud Storageplat_iosplat_androidplat_webplat_cppplat_unity


Cloud Storage is built for app developers who need to store and serve user-generated content, such as photos or videos.
Cloud Storage for Firebase is a powerful, simple, and cost-effective object storage service built for Google scale. The Firebase SDKs for Cloud Storage add Google security to file uploads and downloads for your Firebase apps, regardless of network quality. You can use our SDKs to store images, audio, video, or other user-generated content. On the server, you can use Google Cloud Storage, to access the same files.

Key capabilities


Robust operationsFirebase SDKs for Cloud Storage perform uploads and downloads regardless of network quality. Uploads and downloads are robust, meaning they restart where they stopped, saving your users time and bandwidth.
Strong securityFirebase SDKs for Cloud Storage integrate with Firebase Authentication to provide simple and intuitive authentication for developers. You can use our declarative security model to allow access based on filename, size, content type, and other metadata.
High scalabilityCloud Storage for Firebase is built for exabyte scale when your app goes viral. Effortlessly grow from prototype to production using the same infrastructure that powers Spotify and Google Photos.

How does it work?


Developers use the Firebase SDKs for Cloud Storage to upload and download files directly from clients. If the network connection is poor, the client is able to retry the operation right where it left off, saving your users time and bandwidth.
Cloud Storage stores your files in a Google Cloud Storage bucket, making them accessible through both Firebase and Google Cloud. This allows you the flexibility to upload and download files from mobile clients via the Firebase SDKs, and do server-side processing such as image filtering or video transcoding using Google Cloud Platform. Cloud Storage scales automatically, meaning that there's no need to migrate to any other provider. Learn more about all the benefits of our integration with Google Cloud Platform.
The Firebase SDKs for Cloud Storage integrate seamlessly with Firebase Authentication to identify users, and we provide a declarative security language that lets you set access controls on individual files or groups of files, so you can make files as public or private as you want.

Implementation path


Integrate the Firebase SDKs for Cloud Storage.Quickly include clients via Gradle, CocoaPods, or a script include.
Create a ReferenceReference the path to a file, such as "images/mountains.png", to upload, download, or delete it.
Upload or DownloadUpload or download to native types in memory or on disk.
Secure your FilesUse Firebase Security Rules for Cloud Storage to secure your files.

Looking to store other types of data?


  • Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.
  • The Firebase Realtime Database stores JSON application data, like game state or chat messages, and synchronizes changes instantly across all connected devices. To learn more about the differences between database options, see Choose a database: Cloud Firestore or Realtime Database.
  • Firebase Remote Config stores developer-specified key-value pairs to change the behavior and appearance of your app without requiring users to download an update.
  • Firebase Hosting hosts the HTML, CSS, and JavaScript for your website as well as other developer-provided assets like graphics, fonts, and icons.

Next steps



Was this page helpful?

Comments

popular

firebase authentication using email/password

ABOUT SANTAN DHARM

HTML5 Tutorial

firebase realtime database