On May 25, a new piece of European data protection legislation came into force: the General Data Protection Regulation, or GDPR.
We know that GDPR compliance is at the top of many of your minds, so we've been working hard over the past few months to ensure that you have the resources you need.
We updated to new, GDPR-friendly terms that includes the Firebase Data Processing and Security Terms. We've also given you a way to specify a Data Processing Officer (DPO) or EU Representative in the Firebase console. If you've already added your project's DPO or EU Rep in the Google Cloud console, you don't need to do it again for Firebase.
It's not just about the GDPR either - we've certified many Firebase products under security standards such as ISO 27001, ISO 27017, ISO 27018 and SOC 1, 2 and 3.
To help you implement privacy best practices we've added a dedicated Privacy and Security in Firebase section, launched a new guide on how to manage Instance IDs, and given you some suggestions on how to clear and export user data and store privacy settings using Firebase tools.
For Google Analytics for Firebase users, we have a new guide on your data management options, new sharing settings within the Firebase console that lets you have more control over your data, and a new API for deleting data associated with an Analytics App Instance ID.
Finally, you may want to check out our Google I/O session on paving the way to using Firebase within your enterprise for more ideas on how to manage user data:
If you have any further questions, don't hesitate to reach out to our support team—we can't offer legal advice, but we'll do what we can to help you out with any specific questions or technical concerns.
We have great news for web developers that use Firebase Cloud Messaging to send notifications to clients! The FCM v1 REST API has integrated fully with the Web Notifications API. This integration allows you to set icons, images, actions and more for your Web notifications from your server! Better yet, as the Web Notifications API continues to grow and change, these options will be immediately available to you. You won't have to wait for an update to FCM to support them!
Below is a sample payload you can send to your web clients on Push API supported browsers. This notification would be useful for a web app that supports image posting. It can encourage users to engage with the app.
{ "message": { "webpush": { "notification": { "title": "Fish Photos 🐟", "body": "Thanks for signing up for Fish Photos! You now will receive fun daily photos of fish!", "icon": "firebase-logo.png", "image": "guppies.jpg", "data": { "notificationType": "fishPhoto", "photoId": "123456" }, "click_action": "https://example.com/fish_photos", "actions": [ { "title": "Like", "action": "like", "icon": "icons/heart.png" }, { "title": "Unsubscribe", "action": "unsubscribe", "icon": "icons/cross.png" } ] } }, "token": "<APP_INSTANCE_REGISTRATION_TOKEN>" } }
Notice that you are able to set new parameters, such as actions, which gives the user different ways to interact with the notification. In the example below, users have the option to choose from actions to like the photo or to unsubscribe.
To handle action clicks in your app, you need to add an event listener in the default firebase-messaging-sw.js file (or your custom service worker). If an action button was clicked, event.action will contain the string that identifies the clicked action. Here's how to handle the "like" and "unsubscribe" events on the client:
like
unsubscribe
// Retrieve an instance of Firebase Messaging so that it can handle background messages. const messaging = firebase.messaging(); // Add an event listener to handle notification clicks self.addEventListener('notificationclick', function(event) { if (event.action === 'like') { // Like button was clicked const photoId = event.notification.data.photoId; like(photoId); } else if (event.action === 'unsubscribe') { // Unsubscribe button was clicked const notificationType = event.notification.data.notificationType; unsubscribe(notificationType); } event.notification.close(); });
The SDK will still handle regular notification clicks and redirect the user to your click_action link if provided. To see more on how to handle click actions on the client, check out the guide.
Since different browsers support different parameters in different platforms, it's important to check out the browser compatibility documentation to ensure your notifications work as intended. Want to learn more about what the Send API can do? Check out the FCM Send API documentation and the Web Notifications API documentation. If you're using the FCM Send API and you incorporate the Web Notifications API in a cool way, then let us know! Find Firebase on Twitter at @Firebase, and Facebook and Google+ by searching "Firebase".
Heading to WWDC this year? Join us at the Firebase party on June 4th as we celebrate with the top iOS developers from around the world.
We're excited to once again throw a party for our community at this year's conference. If you're going to be in town, join us for a night to mingle with other developers, meet engineers and product leads from the Firebase team, and relax after the first day of WWDC.
We look forward to hearing about all the cool stuff you've been working on.
Tickets are limited so request your invite today! (Note: a confirmed ticket is required for entry)
In today's fast-moving world, people have come to expect mobile apps to be intelligent - adapting to users' activity or delighting them with surprising smarts. As a result, we think machine learning will become an essential tool in mobile development. That's why on Tuesday at Google I/O, we introduced ML Kit in beta: a new SDK that brings Google's machine learning expertise to mobile developers in a powerful, yet easy-to-use package on Firebase. We couldn't be more excited!
Getting started with machine learning can be difficult for many developers. Typically, new ML developers spend countless hours learning the intricacies of implementing low-level models, using frameworks, and more. Even for the seasoned expert, adapting and optimizing models to run on mobile devices can be a huge undertaking. Beyond the machine learning complexities, sourcing training data can be an expensive and time consuming process, especially when considering a global audience.
With ML Kit, you can use machine learning to build compelling features, on Android and iOS, regardless of your machine learning expertise. More details below!
If you are a beginner or want to implement a solution quickly, ML Kit gives you five ready-to-use ("base") APIs that address common mobile use cases:
With these base APIs, you simply pass in data to ML Kit and get back an intuitive response. For example: Lose It!, one of our early users, used ML Kit to build several features in the latest version of their calorie tracker app. Using our text recognition based API and a custom built model, their app can quickly capture nutrition information from product labels to input a food's content from an image.
ML Kit gives you both on-device and Cloud APIs, all in a common and simple interface, allowing you to choose the ones that fit your requirements best. The on-device APIs process data quickly and will work even when there's no network connection, while the cloud-based APIs leverage the power of Google Cloud Platform's machine learning technology to give a higher level of accuracy.
See these ready-to-use APIs in the Firebase console:
Heads up: We're planning to release two more APIs in the coming months. First is a smart reply API allowing you to support contextual messaging replies in your app, and the second is a high density face contour addition to the face detection API. Sign up here to give them a try!
If you're seasoned in machine learning and you don't find a base API that covers your use case, ML Kit lets you deploy your own TensorFlow Lite models. You simply upload them via the Firebase console, and we'll take care of hosting and serving them to your app's users. This way you can keep your models out of your APK/bundles which reduces your app install size. Also, because ML Kit serves your model dynamically, you can always update your model without having to re-publish your apps.
But there is more. As apps have grown to do more, their size has increased, harming app store install rates, and with the potential to cost users more in data overages. Machine learning can further exacerbate this trend since models can reach 10's of megabytes in size. So we decided to invest in model compression. Specifically, we are experimenting with a feature that allows you to upload a full TensorFlow model, along with training data, and receive in return a compressed TensorFlow Lite model. The technology behind this is evolving rapidly and so we are looking for a few developers to try it and give us feedback. If you are interested, please sign up here.
Since ML Kit is available through Firebase, it's easy for you to take advantage of the broader Firebase platform. For example, Remote Config and A/B testing lets you experiment with multiple custom models. You can dynamically switch values in your app, making it a great fit to swap the custom models you want your users to use on the fly. You can even create population segments and experiment with several models in parallel.
Other examples include:
We can't wait to see what you'll build with ML Kit. We hope you'll love the product like many of our early customers:
Get started with the ML Kit beta by visiting your Firebase console today. If you have any thoughts or feedback, feel free to let us know - we're always listening!
It’s hard to believe that it’s only been two years since we expanded Firebase at I/O 2016 from a set of backend services to a full app development platform. In the time since then, it’s been humbling to watch the developer community embrace Firebase. We now have 1.2 million apps actively using Firebase every month!
No matter how much we grow, our mission remains the same: to help mobile app teams be successful across every stage of your development cycle, from building your app, to improving app quality, to growing your business.
Having such an amazing developer community is both a huge honor and a huge responsibility. Thank you for trusting us with your apps. It’s inspiring to hear the stories about what you’ve built with Firebase and your success is the reason we’re excited to come to work everyday!
Today, we’re announcing a number of improvements to Firebase. Let’s take a look.
Machine learning just got easier for mobile developers. We’re excited to announce ML Kit, an SDK available on Firebase that lets you bring powerful machine learning features to your app whether it's on Android or iOS, and whether you're an experienced ML developer or you're just getting started.
ML Kit comes with a set of ready-to-use APIs for common use cases: recognizing text, detecting faces, scanning barcodes, labeling images and recognizing landmarks. These APIs can run on-device or in the cloud, depending on the functionality. The on-device APIs process data quickly and will work even when there's no network connection, while the cloud-based APIs leverage the power of Google Cloud Platform's machine learning technology to give a higher level of accuracy. You can also bring in your own TensorFlow Lite models for advanced use-cases, and ML Kit will take care of the hosting and serving, letting you focus on building your app.
These five APIs are just the first step. We'll be rolling out more in the future and if you want to be involved as an early tester, please visit our signup form to join the waiting list.
Whether you're building on Android or iOS, you can improve the experience for your users by leveraging machine learning. And with ML Kit, we hope to make it easy for developers of all experience levels to get started today. Visit our docs to learn more.
At I/O last year, we launched Performance Monitoring into beta to help you gain insight into your app's performance so you can keep it fast and responsive. Since then, we've seen tremendous adoption. Some of the largest apps in the world — like Flipkart, Ola, and Swiggy — have started using Performance Monitoring and we now report 100 billion performance metrics every day, helping developers improve their app's quality and make their users happy!
Now that the SDK is battle-tested, we've decided to graduate Performance Monitoring out of beta. With this change comes a couple of improvements that you'll see rolling out into the console today.
First, you'll now see an issues feed at the top of the Performance Monitoring dashboard. This feed gives you a quick and easy look at any performance issues occurring across your app, as well as Firebase's opinion on the severity of the issue.
Second, you can now easily identify parts of your app that stutter or freeze. Performance monitoring identifies rendering issues, telling you how many frames are dropped per screen in your app, so you can quickly troubleshoot the issue. If you have apps in the Play store, this is a great way to get detailed information on rendering issues reported in Android vitals, without writing additional code. You can get started with Performance Monitoring today by visiting our documentation.
With Google Analytics for Firebase, you've always been able to see analytics for each of your project's apps. Last year, we added the ability to see your data in real time, with the addition of the StreamView and DebugView reports. Now, you'll notice that we've added real time cards throughout your Analytics reports to give you a better idea of what your users are doing right now.
Analytics is also getting two more upgrades with the addition of project level reporting and flexible filters. Project level reporting lets you see what's happening across all the apps in a project, so you have a more holistic view of your app business, while flexible filters allows you to slice your data more precisely to produce key insights. These updates will be rolling out in the coming weeks.
We're launching another update to the Firebase console today: improved identity and access management. This will allow you to more easily invite others to collaborate on your projects and control what they have access to, all from within the Firebase console.
At Firebase, it's always been vitally important to us to build products that work for development on both Android and iOS. That's why it's particularly exciting to announce that we're expanding Test Lab to include iOS, in addition to Android.
Test Lab provides you with physical and virtual devices that allow you to run tests to simulate actual usage environments. With the addition of Test Lab for iOS, we help you get your app into a high quality state - across both Android and iOS - before you even release it.
Test Lab for iOS will be rolling out over the coming months. If you want to be an early tester of the product, you can sign-up in this form to get on the waiting list today.
It’s been an amazing journey at Firebase so far and we believe that we’re only getting started. By continuing to deepen our integrations with Google Cloud Platform, we aim to make it easy for you to leverage the enormous scale of Google’s infrastructure. We’re also immensely excited about the possibilities that machine learning holds for empowering developers like you. Predictions and ML Kit are the first two steps, but there’s much more we hope to do.
Thank you, as always, for being part of the journey with us. To hear about many of these announcements and more in detail, you can check out our YouTube playlist for recordings of all our talks at Google I/O. If you’re not already part of the Firebase Alpha program, please join and help shape the future of the platform. We can’t wait to see what you build next.
In 2016, we unveiled Firebase Cloud Messaging (FCM) as the next evolution of Google Cloud Messaging (GCM). Since then, we've been working hard to make Firebase Cloud Messaging even more powerful than its predecessor. Like GCM, Firebase Cloud Messaging allows you to send notifications and data messages reliably to iOS, Android, and the Web at no cost. In addition, FCM includes a host of new features, such as an intuitive notifications interface in the Firebase console, better reporting, and native integrations with other Firebase products. With FCM, you can target and test notifications to re-engage your users with greater ease and efficiency.
We're excited to devote more time and attention to improving FCM. That's why today we're announcing that all developers will need to upgrade to FCM within a year. The GCM server and client APIs have been deprecated and will be removed as soon as April 11th, 2019. We recommend you upgrade sooner rather than later so you can start taking advantage of the new features we're building in FCM right away!
To help you through the upgrade, we've created a step-by-step migration guide and answered a few of the most common questions you'll probably have below.
What else is new in FCM?
Once you upgrade, you'll be able to use all of the new features and functionality available in FCM, like platform overrides and topic combinations. You'll also be able to send notifications directly from the Firebase console! What's more, FCM integrates seamlessly with other Firebase products like A/B Testing and Predictions.
Want to test different messages to see which one drives more conversions? You can use FCM with A/B Testing to run experiments to optimize your notifications. Want to engage users who are likely to churn or spend money in your app? You can use FCM with Predictions to target notifications to users based on their predicted behavior.
These are some of the awesome features you'll have at your fingertips with FCM. In the future, we'll be adding many more!
Will I still be able to send messages to my existing users?
If you have projects that are still using the GCM APIs, you will need to update your client and server code to use FCM before April 11, 2019. But rest assured, your existing GCM tokens will continue to work with FCM so you won't lose the ability to send messages to your existing users.
How do I upgrade?
The full process is outlined in our migration guide, or if you prefer video content, you can also check out this Firecast for details.
On a high level, upgrading consists of three main parts: console-side, app-side, and server-side.
Keep in mind that you don't have to complete all three parts of the process in one sitting - you can take it at your own pace. For example, you can choose to configure the console today and work on the app code another time. You're also free to update your app's code right now, and tackle the server-side requirements later.
What happens to my users who don't update their apps?
As long as users have GCM logic in their apps, they will still receive messages. FCM is backwards compatible with GCM, so even if you don't update your server endpoint now, you can still update your app's logic, and vice versa.
What data will Firebase collect and use? I'm concerned about privacy.
Please see the Firebase terms and the Firebase Privacy and Security Policy. You can disable Google Analytics for Firebase to reduce the amount of data that is collected, but keep in mind this will also disable some FCM features.
What if I still have questions?
We're here to help you through the upgrade process. Check out this nifty FAQ page as a start. We also encourage you to post your questions on StackOverflow. Or, feel free to reach out to Firebase support through any of these means.
To save you clicking time, here are some of the links that are also worth a read. Start with the upgrade guide, and then check out the other links to find out more.
What if I already migrated?
Awesome! How'd it go? Tweet me at @ThatJenPerson to tell me what went well and what didn't. Sharing your experience helps us make improvements!
We look forward to welcoming you to FCM, the next evolution of GCM!
Last year, we launched the beta of Cloud Functions for Firebase to help you build backend functionality for your app without worrying about managing servers. It lets you write in JavaScript or Typescript, deploy to Google's Cloud infrastructure, and execute in response to app events. Today we're pleased to release version 1.0 of the Cloud Functions for Firebase SDK - along with new, frequently requested improvements for the development, testing and monitoring of Functions.
The Firebase SDK for Google Cloud Functions enables you to extend other Firebase products, giving users the features they need in your apps. One of our earliest customers, Posse, makers of the Hamilton app, needed to create a lottery system to give fans a chance to win tickets to the massively popular Broadway play - without the overhead of managing their own servers. When a user enters the lottery, Functions powered logic runs in the cloud with results stored directly to Cloud Firestore. Lottery results are pushed automatically to lucky fans' Hamilton mobile app.
Posse also needed to scale the Hamilton app. When the lottery opens, the app's usage can suddenly surge multifold before normalizing a few minutes later. Functions automatically scales without needing any action from Posse, and their client only pays for the resources they use.
In addition to ticket lotteries, Posse also used Functions to integrate with other Firebase products to:
There's a great deal of things you can do with Functions. For more use cases and sample code, see our popular GitHub repo.
Today's v1.0 release comes with a number of new features based on your feedback - here's the lowdown!
One of your biggest requests was for an easy way to directly call Functions from your client apps. To facilitate that, we're adding a new type of function, along with SDKs for iOS, Android, and web clients. The new type is a Callable HTTPS function that manages an HTTPS request from the client SDK. Callable HTTPS functions drastically reduce the amount of boilerplate code you have to write to make HTTPS requests to Functions.
Here's how it works:
For more, check out our docs!
While Functions Shell gave you the ability to interact with your functions locally, it was not optimal for writing unit tests such as those that run in a CI system. That's why we are launching a new firebase-functions-test npm module that simplifies writing unit tests. firebase-functions-test takes care of the necessary setup and teardown, allowing easy mocking of test data. Now, you can either write completely offline tests that have no side effects, or tests that interact with a development Firebase project - where you can observe the success of actions such as database writes.
Last fall, we introduced the ability to emulate your functions locally via the Firebase CLI through both the "firebase serve --only functions" and "firebase experimental:functions:shell" command. These were experimental features, and now we are officially supporting them. "firebase experimental:functions:shell" has been renamed to "firebase functions:shell", and "firebase serve" will emulate all HTTPS functions by default without the need for the "--only" flag.
After deploying functions, you may be wondering: "What's happening with my functions? How is my app performing? Is anything broken?" With today's release, you can now keep tabs on any errors in your functions via the new health monitor:
Additionally, you can track your functions' performance, latency and memory usage:
The APIs for writing Cloud Functions with the Firebase SDK have changed in this v1.0 SDK release. This means that upgrading to the new SDK will require some updates to any code you've already written during the beta. But don't worry - this doesn't affect any functions you have already deployed. To see what has changed and how to adapt to the new format, just follow our migration guide!
If you're just getting started with the Firebase SDKs for Cloud Functions, try following our step-by-step Codelab and visiting the documentation. There is also a video tutorial to help get you set up using TypeScript as the recommended programming language.
We hope you find these new features helpful. While the Firebase SDKs for Cloud Functions are fully released, the Cloud Functions platform is still in beta. Stay tuned for more updates!
We launched the Google URL Shortener back in 2009 as a way to help people more easily share links and measure traffic online. Since then, many popular URL shortening services have emerged and the ways people find content on the Internet have also changed dramatically, from primarily desktop webpages to apps, mobile devices, home assistants, and more.
To refocus our efforts, we're turning down support for goo.gl over the coming weeks and replacing it with Firebase Dynamic Links (FDL). FDLs are smart URLs that allow you to send existing and potential users to any location within an iOS, Android or web app. We're excited to grow and improve the product going forward. While most features of goo.gl will eventually sunset, all existing links will continue to redirect to the intended destination.
Starting April 13, 2018, anonymous users and users who have never created short links before today will not be able to create new short links via the goo.gl console. If you are looking to create new short links, we recommend you use Firebase Dynamic Links or check out popular services like Bitly and Ow.ly as an alternative.
If you have existing goo.gl short links, you can continue to use all features of goo.gl console for a period of one year, until March 30, 2019, when we will discontinue the console. You can manage all your short links and their analytics through the goo.gl console during this period.
After March 30, 2019, all links will continue to redirect to the intended destination. Your existing short links will not be migrated to the Firebase console, however, you will be able to export your link information from the goo.gl console.
Starting May 30, 2018, only projects that have accessed URL Shortener APIs before today can create short links. To create new short links, we recommend FDL APIs. FDL short links will automatically detect the user's platform and send the user to either the web or your app, as appropriate.
If you are already calling URL Shortener APIs to manage goo.gl short links, you can continue to use them for a period of one year, until March 30, 2019, when we will discontinue the APIs.
As it is for consumers, all links will continue to redirect to the intended destination after March 30, 2019. However, existing short links will not be migrated to the Firebase console/API.
URL Shortener has been a great tool that we're proud to have built. As we look towards the future, we're excited about the possibilities of Firebase Dynamic Links, particularly when it comes to dynamic platform detection and links that survive the app installation process. We hope you are too!
All too often I become frustrated when building an authentication component. The asynchronous flow is hard to manage and it makes my template a mess of ngIfs and Elvis operators:
{{ (user | async)?.uid }}
The problem is always same. I'm mixing too many concerns in one place. Organizing the right code in the right place is what makes a happy codebase.
The solution: Store route specific code in Angular's Route Guards.
The AngularFireAuth service is a great match for routing code. It contains information about a current user, whether they are coming from a redirect, and all sorts of other things.
AngularFireAuth
Take a simple signInWithRedirect example:
signInWithRedirect
import { Component, OnInit } from '@angular/core'; import { AngularFireAuth } from 'angularfire2/auth'; import { Router } from '@angular/router'; import * as firebase from 'firebase/app'; @Component({ selector: 'app-login', template: ` <button class="btn" (click)="auth()"> Login </button> `, styleUrls: ['./login.scss'] }) export class LoginComponent implements OnInit { constructor( private afAuth: AngularFireAuth, private router: Router ) { } ngOnInit() { this.afAuth.getRedirectResult().then(result => { if(result) { this.router.navigateByUrl('profile'); } }); } auth() { const provider = new firebase.auth.GoogleAuthProvider(); this.afAuth.auth.signInWithRedirect(provider); } }
Here's what's going in this example:
auth()
signInWithRedirect()
getRedirectResult()
ngOnInit()
navigateByUrl()
This isn't a problem with one component. However, imagine having to manage redirects in multiple components.
The code in ngOnInit belongs in a Route Guard. This will clean up the component of routing logic and remove the Router dependency entirely.
ngOnInit
Router
A Route Guard is used for all sorts of useful things. In this case a guard can handle the redirect code.
@Injectable() export class RedirectGuard implements CanActivate { constructor( private authService: AngularFireAuth, private router: Router ) {} canActivate() { this.authService.auth.getRedirectResult().then(result => { if(result.user != null) { this.router.navigateByUrl('profile'); return false; } return true; }); } }
The canActivate method determined if the user has access to the route. Here's what happens:
canActivate
'profile'
This code is now reusable. The Angular Router lets you specify which routes you want to listen for a redirect.
import { Routes, RouterModule } from '@angular/router'; import { LoginComponent } from './login/login.component'; import { RedirectGuard } from './redirect.guard'; const ROUTES: Routes = [ { path: '', component: LoginComponent, canActivate: [RedirectGuard] }, { path: 'profile', loadChildren: 'app/profile/profile.module#ProfileModule' } ]; const AppRoutes = RouterModule.forRoot(ROUTES); export { AppRoutes }
Now the LoginComponent is free of routing code:
LoginComponent
@Component({ selector: 'app-login', template: ` <button class="btn" (click)="auth()"> Login </button> `, styleUrls: ['./login.scss'] }) export class LoginComponent { constructor(private afAuth: AngularFireAuth) { } auth() { const provider = new firebase.auth.GoogleAuthProvider(); this.afAuth.auth.signInWithRedirect(provider); } }
No more async flow mess. The right code is organized in the right place. You can add the RedirectGuard to more routes as the app grows, which keeps the complexity out of your components.
RedirectGuard
Dashboards are great, but what if you're not checking them? Wouldn't it be great to know when you have a huge spike in traffic, or if you're about to hit your concurrent connections limit for a single database? Don't worry, Google Stackdriver Alerts have you covered!
Back in December, we announced that the Firebase Realtime Database has integrated with Google Stackdriver to let you create dashboards and graphs of powerful new metrics. We also have more in-depth descriptions of these metrics available in our documentation, as well as other monitoring and debugging tips for your databases. Now we've made all this data actionable through Google Stackdriver Alerts!
You can set alerts that will trigger actions whenever particular conditions are met. For example, if the metric io/database_load goes over 90% for more than one minute, an email will go out to your engineering team. It's also possible to include documentation in your alert, which can help if you haven't yet had your morning coffee. To learn more about conditions that can trigger alerts, see the Condition details documentation.
io/database_load
In addition to the plethora of available conditions, Google Stackdriver also lets you choose how to be alerted. On the basic tier, you can be notified via email or the Google Cloud Console Mobile App. On the premium tier, you're able to create an incident via PagerDuty or have a message posted to your Slack Channel. One of my personal favorite premium notifications is the Webhook option, which you can even use to trigger a Cloud Function to help you diagnose the issue. For the load example, when your database is nearing 100% load, you could start a Cloud Function, have it profile your database, then report the findings to your Slack Channel.
Setting up a custom alert in Stackdriver is a straightforward process. Start by heading over to the Stackdriver Monitoring Console. Once you've signed up for an account, navigate to Alerting > Create a Policy. You should see a panel like this:
For this alerting policy, I've specified that when my database utilization is over 90% for more than a minute, I'll receive an email at alerts@you.com with the name of the policy, plus the documentation I specified. Now all I need to do is hit the Save Policy button, and my alert is live!
Firebase is returning to the Game Developers Conference this year in San Francisco! We've been hard at work making Firebase more valuable for all you game developers out there, and would love to spend time talking with you about how we can make it even better.
While we'll be available to chat at booth 823 for the rest of the conference, we also dropped by the Google Developer Day on Monday to share a few exciting announcements with everybody. In case you missed it, here's the quick summary:
Firebase Auth already lets your players log in safely and securely through a variety of ways -- everything from using their Facebook or Google account to a custom email and password -- but we've now added support for players to sign in using Google Play Games Services (GPGS).
If you're currently using GPGS in your game, you can use the credentials you already have to authenticate your users' accounts with the Firebase service. And if you haven't used GPGS in your Android games yet, you really should because it's an easy -- and often frictionless -- way to get your players signed in. Either way, this means your game can start using Firebase to store user-specific data in Realtime Database or Cloud Storage as soon as your players are signed in through GPGS.
While many of you are developing games for mobile devices, we know that it's often much more convenient to build and test your game on a desktop machine. With that in mind, we've added desktop support so that Firebase will work right from your development environment (Unity player on a Windows machine, for example). This support includes products like:
So if your game relies on one of these products, you can continue to use the same development process you always have, without the hassle of deploying your game on a device every time you want to test it.
Note that desktop support is intended to make development and testing easier, but it's not for publishing Firebase-enabled games to end users on desktop machines.
We debuted Firebase Predictions and A/B Testing at the Firebase Developer Summit in Amsterdam a few months ago, but we think both of these features are so useful to game developers that we want to mention them again. :)
Firebase Predictions brings the power of machine learning to Firebase. By analyzing your players' behavior, we can predict which ones will be most likely to churn out, spend money, or perform any other conversion event that you've defined in Analytics. This allows you to customize your app's behavior (using Remote Config or Notifications) specifically to that group of users. Want to engage players who are likely to stop playing your game? Give them extra lives, or send them a free gift they can redeem inside your game! Want to target players who are likely to spend money on in-app purchases? Notify them about a big sale, or change the layout of your in-app store!
In fact, Rockbite Studios did just that. They used Remote Config to feature certain items at the top of their in-app store for players who were predicted to spend money in their game, while also adding new ad-viewing options for players who were predicted to not spend money. As a result, they boosted revenue by 25% for their spenders, and 24% for their non-spenders!
Firebase A/B testing is great way to improve your game by making data-driven decisions based on experiments that you can run inside your app. Want to know if increasing the difficulty of your game will increase or decrease player engagement? Curious to learn if increasing the amount of premium currency your players start off with will increase or decrease your overall revenue? You can run experiments to uncover answers to all of these questions (and much much more) through Firebase A/B testing.
Firebase A/B testing is easy to get started with, as it runs on top of Remote Config and Analytics, which you might already be using. Experiments can be set up entirely through the Firebase console, which means your game designers or analysts can build, publish, and analyze experiments on their own without needing too much time from your engineering team. And it's all available at no cost to you, which is always nice.
If you want to learn more about how Firebase can make it easier for you to build successful games, come talk to us! We'll be available at booth 823 all during the expo, and we're giving a special presentation on what's new with Firebase and the Google Cloud Platform on Wednesday, March 21st, at 3:30 in the South Hall.
And of course, you can always find out more at https://firebase.google.com/games/
Game on!
Firebase Remote Config is a simple way for you to change elements of your app on the fly, just by using the Firebase console. As developers used Remote Config, many of you requested the ability to change these values without having to go through the Firebase console at all. We're happy to announce that you can now update your Remote Config values directly through the new Remote Config REST API.
The API itself consists of two calls: one to retrieve the current set of Remote Config values from the console, and another to set them. And to be clear, these are designed only for the purpose of setting remote config values without going through the Firebase console. If you want your clients to retrieve these values, they should do so through the native mobile client SDKs.
With this new API, you have the ability to make Remote Config more useful for your team, by creating in-house tools that incorporate specific logic that would be impossible to do from the Firebase console alone. Some examples include:
...and you've probably got a great idea or two we haven't even thought of yet.
The REST API is available starting today for anybody who wants to use it with their project, so give it a try! As always, if you have any questions about the REST API, or just want to show off some fun new tool you've built, please contact us in the Firebase Talk group, or on Stack Overflow.
You have questions about Firebase, and the Firebase community has answers!
But do you know the best place to get your questions answered?
It can be kind of overwhelming to figure out which destination is the best for your particular question. What I'd like to explore today are your options, and how to choose the best one. Choosing the best (and knowing how best to ask) could give you a huge advantage in getting the answers you need. There are five leading options, each with a different purpose. Let's explore those options!
It might seems silly to say, but I think your question should start with a Google search. A well-constructed search could surface existing answers in some of the forums I'll discuss next. You can't pass up the chance of getting your question answered immediately because someone else asked it first!
Try entering your question directly into the search box. Or, if you have an error message in your code, try copying it in there. For exact error messages, sometimes it's helpful to put your search string in quotes to force the most relevant matches to the top of the results.
Bear in mind that not every search yields good results. In some cases, you might stumble across something so rare that only one other person has ever seen it!
That time I searched for "ERROR: Walrus not found: have you checked the polar ice caps?"
If a search doesn't give what you're looking for, it's time to choose from some other options.
But before we continue - if you end up deciding that your question is appropriate for multiple forums, be sure to state that you've cross-posted your question. That gives everyone a chance to figure out which forum may be the best options, and if the question has already been answered elsewhere. That saves everyone time.
Stack Overflow is great for programming questions. In fact, that's the only kind of question you're supposed to ask there. Many Firebase team members pay attention there, including members of the greater community. There are a few tips to making the best of your question on SO:
Not all questions are good for Stack Overflow. In particular, your question may be closed by the community if it's any of the following:
If your question is closed by the community, it will almost certainly not be answered. But don't worry: for questions about Firebase that don't follow the Stack Overflow requirements, there are other options!
Quora is great for general questions, especially those seeking recommendations and opinions. There doesn't have to be a "correct" answer to a question on Quora. It's OK to ask broad questions.
If you choose Quora, be sure to tag your question with the Firebase topic so it's more likely to get noticed by people who have experience with Firebase.
firebase-talk is a long-standing mailing list for people who are looking for open-ended discussion about all things Firebase. It's great for open-ended discussions that require a lot of text that goes back and forth between group members. Many Firebase team members scan the messages here.
When you post your first message here, be prepared to wait for some time for a moderator to accept it.
The Firebase Slack is where Firebase enthusiasts gather to talk about, well, Firebase! This is good for general chit-chat and gathering opinions. While some Firebase team members check in from time to time, it's not an official support channel. So if you have a question that better fits Stack Overflow or Quora, I think it's better to ask there first.
One notable exception is the Firebase Test Lab team who use the #test-lab channel for direct support.
Here's a couple tips for using the Firebase Slack effectively:
This is a good place to ask for urgent issues such as problems with your production app. It's also good for troubleshooting if you require some back and forth with a real person with a problem that can be reproduced in code. You can expect a response from support within 24 hours of asking your question.
Firebase support also handles bug reports and feature requests. So if you have one of those, please fill out the form in that link.
If you want a timely response, I would avoid the following destinations for general questions:
The other reason I would avoid these is because they have limited visibility to the world, whereas the destinations above are well known by the Firebase community. You probably want your question to reach the maximum number of people as possible, in order to get answered quickly.
However, we do encourage you to use Twitter and other social media to broadcast the questions you ask on other sites. For example, it's good to ask a question on Stack Overflow or Quora, then tweet the URL of the question with the hashtag #AskFirebase. Your questions may get picked up for use on the Firebase channel on YouTube.
The Firebase community loves to help with Firebase! And it's easier to get help if you follow the guidelines here to make sure your questions reach the correct audience.
Now watch this video with Kato Richardson, who loves our Firebase community!
I'm always amazed when I think about the fact that Firebase Cloud Messaging sends billions of messages a day. Developers on iOS, Android, and web rely on FCM to send notifications and data messages to their clients. We recently updated FCM to incorporate better security and new features, and now you can access the new FCM through the Firebase Admin SDK for Node.js, Python, Java, and Go.
The latest version of FCM, called FCM v1, includes the ability to send a single request with platform-specific overrides. For example, you can set a time to live for an Android notification and an APNs priority for an iOS notification in the same body. See the documentation or this blog post for more information on platform overrides.
You can now conveniently integrate your server-side applications with the FCM v1 API using the Firebase Admin SDKs. Here's how you can send a simple data message in Node.js:
var registrationToken = 'YOUR_REGISTRATION_TOKEN'; var message = { data: { score: '850', time: '2:45' }, token: registrationToken }; admin.messaging().send(message) .then((response) => { console.log('Successfully sent message:', response); }) .catch((error) => { console.log('Error sending message:', error); });
To see this code in Java, Python, and Go, check the documentation. To see all message payload options, check out the FCM v1 documentation. In addition to sending messages to devices and topics, the Admin SDK for FCM also allows you to manage topic subscriptions from your server.
Here's an example of subscribing to a topic in Node.js:
var registrationTokens = [ 'YOUR_REGISTRATION_TOKEN_1', // ... 'YOUR_REGISTRATION_TOKEN_n' ]; admin.messaging().subscribeToTopic(registrationTokens, topic) .then(function(response) { console.log('Successfully subscribed to topic:', response); }) .catch(function(error) { console.log('Error subscribing to topic:', error); });
To see this code in Java, Python, and Go, check the documentation. Thanks to the Admin SDK, it's even easier than ever to send messages! Check out the full documentation here. And if you build something cool with FCM, be sure to tell us about it! Tweet @Firebase and @ThatJenPerson and let us know how it's going!
Securing your Firebase Realtime Database just got easier with our newest feature: query-based rules. Query-based rules allow you to limit access to a subset of data. Need to restrict a query to return a maximum of 10 records? Want to ensure users are only retrieving the first 20 records instead of the last 20? Want to let a user query for only their documents? Not a problem. Query-based rules has you covered. Query-based rules can even help you simplify your data structure. Read on to learn how!
query
Security rules come with a set of variables that help you protect your data. For instance, the auth variable tells you if a user is authenticated and who they are, and the now allows you to check against the current server time.
auth
now
Now, with the query variable, you can restrict read access based on properties of the query being issued.
messages: { ".read": "query.orderByKey && query.limitToFirst <= 100" }
In the example above a client can read the messages location only if they issue an orderByKey() query that limits the dataset to 100 or less. If the client asks for more than 100 messages the read will fail.
messages
orderByKey()
The query variable contains additional properties for every type of query combination: orderByKey, orderByChild, orderByValue, orderByPriority, startAt, endAt, equalTo, limitToFirst, and limitToLast. Using a combination of these properties you can restrict your read access to whatever criteria you need. Get the full reference and see more examples in our docs.
orderByKey
orderByChild
orderByValue
orderByPriority
startAt
endAt
equalTo
limitToFirst
limitToLast
Another benefit of query-based rules is that they make it easier to manage a shallow data structure.
In the past you might index your items location by a user's id.
items
{ "items": { "user_one": { "item_one": { "text": "Query-based, rules!" } } } }
This structure made it easy to query and restrict item reads on a per-user basis.
{ "rules": { "items": { "$uid": { ".read": "auth.uid == $uid" } } } }
This is great because your user's items are secured, but it requires you to index off of the user's id, potentially replicating data or complicating your client code.
With query-based rules, you can now get the same security without the nesting!
{ "rules": { "items": { ".read": "auth.uid != null && query.orderByChild == 'uid' && query.equalTo == auth.uid" } } }
The above rule will restrict any read on a per-user basis without indexing by the "uid" key, which means you can write a simple query to retrieve a user's items without sacrificing security.
"uid"
Now the data structure is reduced by one level:
```
{ "items": { "item_one": { "text": "Query-based, rules!", "uid": "user_one" } } }
``
db.ref("items").orderByChild("uid") .equalTo(auth.currentUser.uid) .on("value", cb)
The above query will retrieve all the items belonging to the currently authenticated user. If a user tries to access items that don't belong to them, the read will fail.
Query expressions are new feature that can be used in parallel with your existing rules. If you find that query expressions can improve your security or simplify your structures you can upgrade to them incrementally.
Query-based rules are available for use today. Go to your Firebase console and use the emulator to give them a whirl. Check out our official documentation for more information. If you run into any problems make sure to check out our support channels or hit up the Firebase Slack community.
When I think back 10 years or so when I was writing code for a monolithic codebase written in C++, one of the worst memories I have of the time was waiting for a build to complete just to run a couple lines of new code. The pain was so common among engineers that it bore the creation of one of the all-time most popular XKCD comics:
My office at the time didn't have swords to play with, so waiting for a build to complete was really boring.
The pain is similar if I had to deploy my Cloud Functions code every time I want test a function. Fortunately, the Firebase CLI now has a local emulator that works for both HTTPS and other types of functions. This lets me run the functions on my development machine by emulating the events that would trigger it. You can read more about that in the documentation.
One of the emulator's handy features is the fact that it will reload any JavaScript files that change over time. So, if you modify the code of a function, you can test it right away in the emulator without having to restart it:
It's fast and easy, and keeps you "in the zone".
However, things become less easy when you switch from JavaScript to TypeScript. Running TypeScript on Cloud Functions requires a compilation phase to convert the TypeScript into JavaScript so that it can be executed by the emulator. It adds a bit of a hassle:
npm run build
There's an easier way to do this that doesn't involve running a command every time. The TypeScript compiler (tsc) has a special "watch mode" that lets it pick up changes to your TypeScript and automatically compile them. You can run it from the command line by changing to your functions folder and running this command:
tsc
./node_modules/.bin/tsc --watch
With this running alongside the local emulator, which automatically picks up changes to the compiled JavaScript, your development workflow goes back to this:
And, if you're using VSCode, you can even have it directly run tsc in watch mode. You can start it up with Tasks -> Run Build Task..., then choosing "tsc: watch".
It will fire up a command shell right in the IDE, run tsc --watch, and show you the output. You'll see messages like this, along with any compilation errors, any time a TypeScript file changes:
tsc --watch
2:38:38 PM - File change detected. Starting incremental compilation... 2:38:38 PM - Compilation complete. Watching for file changes.
Now, bear in mind that tsc in watch mode won't run TSLint against your code, so be sure to set that up in VSCode so you can always see its recommendations, as I showed in a prior blog post. If you're not linting your code, seriously consider setting that up, because you'll catch potential mistakes that could be costly in production.
Are you looking for something new to learn this year? Then let me suggest TypeScript for development with Cloud Functions!
Not long ago, the Cloud Functions for Firebase team released an update to the Firebase CLI that makes it easy for you to write your functions in TypeScript, rather than JavaScript. The Firebase team encourages you to consider switching to TypeScript, but I can imagine you might be reluctant to learn a new language, especially if you're already comfortable with JavaScript. The great news is that TypeScript offers you a bunch of benefits that are easy to start using today.
The language itself offers a bunch of features that make your code easier to read and write, and less error-prone:
There's also async/await from ECMAScript 2017, which helps you write asynchronous code more easily. The primary challenge with asynchronous code is management of promises, which is crucial to get right when writing Cloud Functions, but difficult to master. TypeScript makes that much easier.
But what I really want to dive into here is an excellent tool called TSLint that can check your TypeScript code for potential problems before you deploy to Cloud Functions. The Firebase CLI will prompt you to configure TSLint when you initialize Functions in a project using TypeScript, and we strongly recommend that you opt into it.
When you opt into TypeScript and TSLint in your Firebase project structure, the Firebase CLI will add and modify some project files when you run firebase init. First let's take a look at functions/package.json. In there, you'll see the following key:
firebase init
functions/package.json
"devDependencies": { "tslint": "^5.8.0", "typescript": "^2.6.2" },
This is where node pulls in TypeScript and TSLint for development. Notice that there are "devDependencies" that are separate from the normal "dependencies" that you use in your function code. devDependencies are only stored on your machine, and are made available as tools for development. They are not deployed with your code. Also in that file, notice there are two script definitions:
"scripts": { "lint": "./node_modules/.bin/tslint -p tslint.json", "build": "./node_modules/.bin/tsc", ... }
These give you the ability to run npm run lint and npm run build on the command line from your functions directory. The first check your code with TSLint, and the second will build it with the TypeScript compiler.
npm run lint
The next file to look at is firebase.json. This now has a predeploy hook that runs TSLint against your code, so if it has an error, the deploy will fail:
firebase.json
{ "functions": { "predeploy": [ "npm --prefix $RESOURCE_DIR run lint", "npm --prefix $RESOURCE_DIR run build" ] } }
The next file is functions/tsconfig.json. This contains the configuration for the TypeScript compiler.
functions/tsconfig.json
{ "compilerOptions": { "lib": ["es6"], "module": "commonjs", "noImplicitReturns": true, "outDir": "lib", "sourceMap": true, "target": "es6" }, "compileOnSave": true, "include": [ "src" ] }
I won't cover all the settings here, but it's important to note that the compiler will look for source TypeScript files under functions/src, and compile them to JavaScript into functions/lib, with ECMAScript 6 compatibility, as required by Cloud Functions. Cloud Functions currently runs Node 6, which means it natively understand ES6 code.
functions/src
functions/lib
Lastly, take a brief look at functions/tslint.json. This lists all the rules that are observed when TSLint checks your code. You can add new rules here, or remove the rules you don't want. I suggest leaving everything there, as the list of rules was curated by the Firebase team to help with writing functions. The "strict errors" whose values are set to true will cause compile time errors if violated. The warnings below that will just complain about possible issues, and it's the team's opinion that you should look into resolving them.
functions/tslint.json
true
Alrightey. Take a look at this function that populates a property called createdAt when a user node is created in Realtime Database. Do you see what's wrong here?
createdAt
export const onUserCreate = functions.database.ref('/users/{uid}').onCreate(event => { event.data.ref.update({ createdAt: Date.now() }) })
TSLint sees the issue, and its one of the most common mistakes made when writing functions. If you run npm run build on this code, you'll see this error in its output:
Promises must be handled appropriately
This error is triggered by the rule no-floating-promises. TSLint sees that event.data.ref.update returns a promise, but nothing is being done with it. The correct way to deal with promises for database triggers is to return it:
event.data.ref.update
export const onUserCreate = functions.database.ref('/users/{uid}').onCreate(event => { return event.data.ref.update({ createdAt: Date.now() }) })
If you're using async/await, you can also declare the function async and use await to return it:
async
await
export const onUserCreate = functions.database.ref('/users/{uid}').onCreate(async event => { await event.data.ref.update({ createdAt: Date.now() }) })
Proper handling of promises is an absolute requirement when dealing with Cloud Functions, and TSLint will point out where you're not doing so.
I do a lot of Android development, and I'm accustomed to Android Studio linting my code as I type it. This is valuable because I get instant feedback about where things could go wrong. On the Firebase team, a bunch of us use VSCode for editing TypeScript, and it will use TSLint to give you instant feedback. The TSLint extension is easy to install.
Go to View -> Extensions. Type "TSLint" into the search box on the left. Find the TSLint extension, and click the Install button. After it's installed, click the Reload button, and now your TypeScript will be marked with possible mistakes.
Here's an HTTPS function that fetches a user document from Firestore using the Admin SDK. It looks OK and works OK:
export const getUser = functions.https.onRequest((req, res) => { var uid = req.params.uid const doc = admin.firestore().doc(`users/${uid}`) doc.get().then(doc => { res.send(doc.data()) }).catch(error => { res.status(500).send(error) }) })
But when viewed in VSCode with TSLint markers, you'll see that it violates some best practices:
Notice the squiggly lines under var, uid, and doc. If you hover the mouse over the marked code, you'll see a message from TSLint:
var
uid
doc
That's TSLint using the prefer-const rule to tell you that it's better to use const instead of var to declare values that don't change. It's good for the readability of your code, and also prevents someone from making an accidental change to it later on.
const
The squiggly line under doc is TSLint using the no-shadowed-variable rule to point out that the doc parameter in the function passed to then() (a DeltaDocumentSnapshot object) is masking the doc constant in the outer scope (a DocumentReference object), making the latter completely unavailable for use. While this is not really a bug here, it can lead to confusion about which doc instance is being referred to at any given moment. Renaming either instance resolves the issue.
then()
Here's a lint-free version of the same function:
export const getUser = functions.https.onRequest((req, res) => { const uid = req.params.uid const doc = admin.firestore().doc(`users/${uid}`) doc.get().then(snapshot => { res.send(snapshot.data()) }).catch(error => { res.status(500).send(error) }) })
This makes TSLint happy, which should make you happy, because you're writing better code!
If you haven't started learning TypeScript yet, 2018 is a fine time to begin. It's easy to get started, because TypeScript is a strict superset of JavaScript, meaning that all your existing JavaScript code is already valid TypeScript. So you can simply rename your .js files to .ts and drop them into functions/src. Then, you can start using TypeScript language features as you wish. Let us know how it goes and shout out to @Firebase on Twitter.