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 --><scriptsrc="/__/firebase/6.4.0/firebase-app.js"></script><!-- Add Firebase products that you want to use --><scriptsrc="/__/firebase/6.4.0/firebase-auth.js"></script><scriptsrc="/__/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 --><scriptsrc="/__/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:
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).
Consideration
Cloud Functions for Firebase
Cloud Run
Setup
The 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 environment
Requires Node.js, but you can specify which versionof Node to use (currently, Node version 6 or 8).
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
Make sure that:
You have the latest version of the Firebase CLI (run npm install -g firebase-tools).
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.
Add the first endpoint to serve the index of our website at /.
app.get('/',(req, res)=>{const date =newDate();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>`);});
And another endpoint to return the BONG count as an API, in JSON format, under /api:
app.get('/api',(req, res)=>{const date =newDate();const hours =(date.getHours()%12)+1;// London is UTC + 1hr;
res.json({bongs:'BONG '.repeat(hours)});});
Export the Express.js app as an HTTP function:
exports.app = functions.https.onRequest(app);
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.
Install the cors middleware by running the following command:
npm install --save cors
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.
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
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
Set up caching for your dynamic content on a global CDN.
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.
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
Enable the Cloud Run API in the Google APIs console:
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
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.
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.
Make sure that:
You have the latest version of the Firebase CLI (run npm install -g firebase-tools).
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)}}]}
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
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.
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:
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-agefor 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.
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:
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.
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:
Click Generate New Private Key, then confirm by clicking Generate Key.
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:
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.
Determine the site-name of the site to which you want to deploy.
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.
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: file1, file2, and file3.
Gzip the files:
gzip file1 && gzip file2 && gzip file3
You now have three compressed files file1.gz, file2.gz, and file3.gz.
You now have the three SHA256 hashes of the three compressed files.
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).
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.
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.
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.
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.
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.
Firebase 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 security
Firebase 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 scalability
Cloud 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 Reference
Reference the path to a file, such as "images/mountains.png", to upload, download, or delete it.
Upload or Download
Upload or download to native types in memory or on disk.
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.
Authenticate with Firebase Using Email Link in JavaScript You can use Firebase Authentication to sign in a user by sending them an email containing a link, which they can click to sign in. In the process, the user's email address is also verified. There are numerous benefits to signing in by email: Low friction sign-up and sign-in. Lower risk of password reuse across applications, which can undermine security of even well-selected passwords. The ability to authenticate a user while also verifying that the user is the legitimate owner of an email address. A user only needs an accessible email account to sign in. No ownership of a phone number or social media account is required. A user can sign in securely without the need to provide (or remember) a password, which can be cumbersome on a mobile device. An existing user who previously signed in with an email identifier (password or federated) can be upgraded to sign in with just the email. For example, a user who has f...
HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a markup language. In this tutorial, we will discuss the features of HTML5 and how to use it in practice. Audience This tutorial has been designed for beginners in HTML5 to make them understand the basic-to-advanced concepts of the subject. Prerequisites Before starting this tutorial, you should have a basic understanding of HTML and its tags. HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web. HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG). The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears. Browse...
Firebase Realtime Database plat_iosplat_androidplat_webplat_cppplat_unity Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline. The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data. iOS setup Android setup Web setup REST API C++ setup Unity setup Admin setup Key capabilities Realtime Instead of typical HTTP requests, the Firebase Realtime Database uses data synchronization—every time data changes, any connected device receives that update within milliseconds. Provide collaborative and immersive experiences without thinking about networking code. Offline Firebase apps remain responsive even when offline because the Fi...
Comments
Post a Comment