Understanding Cloud Functions

Google Cloud Functions is a lightweight compute solution for developers to create single-purpose, stand-alone functions that respond to Cloud events without the need to manage a server or runtime environment.

Welcome back to another episode of Cloud Functions for Firebase. In the last episode, Doug showed you how global memory and temp disk space was retained between function invocations on the same server instance. In this episode, you will learn how to safely code for your functions that will run in parallel on multiple instances. Check out the resource below to find out more information, and subscribe to the Firebase channel for more app development tutorials!

Cloud Functions Execution Environment docs → http://bit.ly/2XghRWu

Retry asynchronous functions → http://bit.ly/2tGtZCh

Modifying function configuration → http://bit.ly/2H5L2GS

Python runtime → http://bit.ly/2TEW1g4

Google Cloud regions → http://bit.ly/2Hmp5m0

Learn More

Angular (Full App) with Angular Material, Angularfire & NgRx

Firebase Firestore for iOS

Firebase as simple database to React app

Firebase as simple database to React app

Push Notification using Ionic 4 and Firebase Cloud Messaging

Build a CRUD App with Angular and Firebase

Push Notifications in PWA (React.js) Using Firebase

Deploying a Node 12 Function to Cloud Run

Deploying a Node 12 Function to Cloud Run

In this post, we’ll learn how to deploy a Node 12 application using the Functions Framework and Cloud Run.

Originally published by Grant Timmerman at https://medium.com

Let’s say this.

  • You learn that the Node Foundation releases cutting-edge
  • Node 12
  • .It includes cool new features like more performant async/await, faster HTTP parsing, and private fields. It’s still in development but you want to use it for your services.But Google Cloud Functions doesn’t support Node 12 yet.

So whatchagunnado?

  • Blog about it?

…Maybe

  • Or use Cloud Run

Let’s learn how to do that!

Deploying a Node 12 Function to Cloud Run

Node is a JavaScript runtime built on Chrome’s V8 engine.

Cloud Run (http://cloud.run) is a managed, serverless computing platform that abstracts away infrastructure management, so you can focus on building great applications.

Together, you can build scalable services atop Google Cloud in minutes.

First, Install Node 12

TJ has an incredibly simple Node module called n for managing Node versions (i.e. switching between 10 and 12). Install the global CLI called n:

sudo npm i n -g

Then switch your Node version to Node 12:

sudo n 12

Verify your Node version

node -v # v12.7.0
Create a Node 12 Function

Create a new package.json:

{
  "name": "ffnode12",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "functions-framework"
  },
  "dependencies": {
    "@google-cloud/functions-framework": "^1.2.1"
  }
}

Hard to make it simpler than that!

Create a class in greeter.js that uses Node 12 private fields:

class Greeter {
  #name = 'Functions Framework';
  get name() {
    return this.#name;
  }
  set name(name) {
    this.#name = name;
  }
  sayHello() {
    return `Hello, ${this.#name}`;
  }
}

module.exports = Greeter;

#private field

Create an index.js file:

const Greeter = require('./greeter');

exports.function = (req, res) => {
const g = new Greeter();

// Can't access private fields
// greet.#name = 'NewName';

res.send(g.sayHello());
};

Private fields are inaccessible!

Test the Functions Framework locally

You’ll want to test your service locally to ensure you code works.

So we got things working locally. But how do we deploy this to Google Cloud? Read on!

Next, we’ll use Cloud Build + Cloud Run

Create a Dockerfile
OK. I’ll be honest. If you asked me 6 months ago what Docker was, I’d mumble something about boxes, container ships, and a blue whale. But…

Docker is really nothing to be afraid of. It is an open platform for developing and running applications. To run an application, you’ll need to create some instructions for Docker to set up your environment.

Create a file called Dockerfile (no file extension) as such:

# Use the official Node.js 12 image.

https://hub.docker.com/_/node

FROM node:12

Create and change to the app directory.

WORKDIR /usr/src/app

Copy application dependency manifests to the container image. A wildcard is used to ensure both package.json AND package-lock.json are copied. Copying this separately prevents re-running npm install on every code change.

COPY package*.json ./

Install production dependencies.

RUN npm install --only=production

Copy local code to the container image.

COPY . .

Run the web service on container startup.

CMD [ "npm", "start" ]

A basic Dockerfile for Node applications

We’ll tell Docker, use Node 12, copy our package.json we defined above, install, copy our files, then start our server!

Deploy to Cloud Run

To deploy to Google’s Cloud Run, follow these 3 steps:

1 - Setup gcloud

# Install gcloud beta services
gcloud components install beta# Set env var "GCP_PROJECT" to our project name
GCP_PROJECT=$(gcloud config list --format 'value(core.project)' 2>/dev/null)# Set our Cloud Run region (so we aren't prompted)
gcloud config set run/region us-central1

2 - Upload your code and build the container

# Build and upload your image in Google Container Registry
gcloud builds submit --tag gcr.io/$GCP_PROJECT/helloworld

Notice each command in the Dockerfile gets executed (~30s)

3 - Deploy to Cloud Run

# Deploy your container to Cloud Run
gcloud beta run deploy --image gcr.io/$GCP_PROJECT/helloworld --platform managed

Deploy our container to Cloud Run (~17s)

You’ll get a URL that looks like this:

https://helloworld-q7vieseilq-uc.a.run.app

Congrats! You deployed the Functions Framework to Cloud Run.



Push Notification using Ionic 4 and Firebase Cloud Messaging

Push Notification using Ionic 4 and Firebase Cloud Messaging

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM)

The comprehensive step by step tutorial on receiving a push notification on Mobile App using Ionic 4 and Firebase Cloud Messaging (FCM). We will use Ionic 4 Cordova native FCM plugin for receiving a push notification and using Firebase API for sending push notification from the Postman.

Table of Contents:

The following tools, frameworks, and modules are required for this tutorial:

Before going to the main steps, we assume that you have to install Node.js. Next, upgrade or install new Ionic 4 CLI by open the terminal or Node command line then type this command.

sudo npm install -g ionic

You will get the latest Ionic CLI in your terminal or command line. Check the version by type this command.

ionic --version
4.10.3

1. Setup and Configure Google Firebase Cloud Messaging

Open your browser then go to Google Firebase Console then login using your Google account.

Next, click on the Add Project button then fill the Project Name with Ionic 4 FCM and check the terms then click Create Project button.

After clicking the continue button you will redirect to the Project Dashboard page. Click the Gear Button on the right of Project Overview then click Project Settings. Click the Cloud Messaging tab the write down the Server Key and Sender ID for next usage in the API and Ionic 4 App. Next, back to the General tab then click the Android icon in your Apps to add Android App.

Fill the required fields in the form as above then click Register App button. Next, download the google-services.json that will use in the Ionic 4 app later. Click next after download, you can skip Add Firebase SDK by click again Next button. You can skip step 4 if there’s no App creating on running yet.

2. Create a new Ionic 4 App

To create a new Ionic 4 App, type this command in your terminal.

ionic start ionic4-push blank --type=angular

If you see this question, just type N for because we will installing or adding Cordova later.

Install the free Ionic Appflow SDK and connect your app? (Y/n) N

Next, go to the newly created app folder.

cd ./ionic4-push

As usual, run the Ionic 4 App for the first time, but before run as lab mode, type this command to install @ionic/lab.

npm install --save-dev @ionic/lab
ionic serve -l

Now, open the browser and you will the Ionic 4 App with the iOS, Android, or Windows view. If you see a normal Ionic 4 blank application, that’s mean you ready to go to the next steps.

3. Add Ionic 4 Cordova Native FCM Plugin

To install Ionic 4 Cordova Native Firebase Message Plugin, type this command.

ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
npm install @ionic-native/fcm

Next, open and edit src/app/app.module.ts then add this import.

import { FCM } from '@ionic-native/fcm/ngx';

Add to @NgModule providers.

providers: [
  StatusBar,
  SplashScreen,
  FCM,
  { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],

Next, open and edit src/app/app.component.ts then add this import.

import { FCM } from '@ionic-native/fcm/ngx';
import { Router } from '@angular/router';

Inject FCM and Router module to the constructor.

constructor(
  private platform: Platform,
  private splashScreen: SplashScreen,
  private statusBar: StatusBar,
  private fcm: FCM,
  private router: Router
) {
  this.initializeApp();
}

Inside platform ready of initializeApp function, add a function to get FCM token then print out to the browser console.

this.fcm.getToken().then(token => {
  console.log(token);
});

Add this function to refresh the FCM token.

this.fcm.onTokenRefresh().subscribe(token => {
  console.log(token);
});

Add this function to receive push notification from Firebase Cloud Messaging.

this.fcm.onNotification().subscribe(data => {
  console.log(data);
  if (data.wasTapped) {
    console.log('Received in background');
    this.router.navigate([data.landing_page, data.price]);
  } else {
    console.log('Received in foreground');
    this.router.navigate([data.landing_page, data.price]);
  }
});

Above example of receiving a push notification from FCM will redirect to the other page with params of data. For that, next, we have to add a new page by type this command.

ionic g page second

Next, modify src/app/app-routing.module.ts then change the new page route.

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: './home/home.module#HomePageModule' },
  { path: 'second/:price', loadChildren: './second/second.module#SecondPageModule' },
];

Next, open and edit src/app/second/second.page.ts then add this import.

import { ActivatedRoute } from '@angular/router';

Inject that module to the constructor.

constructor(private route: ActivatedRoute) { }

Add a variable for hold data from router parameters.

price: any = '';

Add this line to get data from the router parameters.

constructor(private route: ActivatedRoute) {
  this.price = this.route.snapshot.params['price'];
}

Next, open and edit src/app/second/second.page.html then replace all HTML tags with this.

<ion-header>
&nbsp; <ion-toolbar>
&nbsp; &nbsp; <ion-title>Second</ion-title>
&nbsp; </ion-toolbar>
</ion-header>

<ion-content padding>
&nbsp; <ion-card>
&nbsp; &nbsp; <ion-card-header>
&nbsp; &nbsp; &nbsp; <ion-card-title>Congratulation!</ion-card-title>
&nbsp; &nbsp; </ion-card-header>

&nbsp; &nbsp; <ion-card-content>
&nbsp; &nbsp; &nbsp; You get price from our sponsor:
&nbsp; &nbsp; &nbsp; <h2>{{price}}</h2>
&nbsp; &nbsp; </ion-card-content>
&nbsp; </ion-card>
</ion-content>

If you plan to send push notification to the group of topic, add this lines inside the platform ready.

this.fcm.subscribeToTopic('people');

To unsubscribe from topic, add this line.

this.fcm.unsubscribeFromTopic('marketing');

4. Run and Test Sending and Receiving Push Notification

Before running this Ionic 4 app, we have to copy the downloaded google-services.json file to the root of the project. Type this command to add the Android platform.

ionic cordova platform add android

Next, copy the google-services.json to the platform/android/ directory.

cp google-services.json platform/android/

Next, run the Ionic 4 App to the Android device by type this command.

ionic cordova run android

After the app running on the device, check the console from the Google Chrome by type this address chrome://inspect then choose the inspect link. You should take to the browser inspector, just change to the console tab.

As you can see above, you can take and write down the FCM token for use by Postman. Next, open the Postman application from your computer. Change the method to POST and add this address [https://fcm.googleapis.com/fcm/send](https://fcm.googleapis.com/fcm/send "https://fcm.googleapis.com/fcm/send"). On the headers, add this key Content-Type with value application/json and Authorization with value key=YOUR_FIREBASE_KEY....

Next, add this JSON data to the RAW body.

{
&nbsp; "notification":{
&nbsp; &nbsp; "title":"Ionic 4 Notification",
&nbsp; &nbsp; "body":"This notification sent from POSTMAN using Firebase HTTP protocol",
&nbsp; &nbsp; "sound":"default",
&nbsp; &nbsp; "click_action":"FCM_PLUGIN_ACTIVITY",
&nbsp; &nbsp; "icon":"fcm_push_icon"
&nbsp; },
&nbsp; "data":{
&nbsp; &nbsp; "landing_page":"second",
&nbsp; &nbsp; "price":"$3,000.00"
&nbsp; },
&nbsp; &nbsp; "to":"eadego-nig0:APA91bEtKx9hv50lmQmfzl-bSDdsZyTQ4RkelInfzxrPcZjJaSgDmok3-WQKV5FBu9hrMrkRrcCmf3arkGSviGltg5CyC2F9x1J2m0W7U8PxJ3Zlh7-_tL6VcFdb76hbaLIdZ-dOK15r",
&nbsp; &nbsp; "priority":"high",
&nbsp; &nbsp; "restricted_package_name":""
}

If you want to send by topics recipients, change the value of to to topics/people. Next, click the send button and you should see this response.

{
&nbsp; &nbsp; "multicast_id": 7712395953543412819,
&nbsp; &nbsp; "success": 1,
&nbsp; &nbsp; "failure": 0,
&nbsp; &nbsp; "canonical_ids": 0,
&nbsp; &nbsp; "results": [
&nbsp; &nbsp; &nbsp; &nbsp; {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "message_id": "0:1550632139317442%b73443ccb73443cc"
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; ]
}

And you will see the notification in your Android device background screen.

If you tap on it, it will open the App and redirect to the second page with this view.

That it’s, the example of receiving push notification using Ionic 4 and Firebase Cloud Messaging. You can grab the full source code from our GitHub.

Flutter Push Notification with Firebase Cloud Messaging

Flutter Push Notification with Firebase Cloud Messaging

In this tutorial, we will learn how to implement Firebase Push Notification with Flutter apps. Flutter Push Notification Tutorial with Example

In this tutorial, we will learn how to implement Firebase Push Notification with Flutter apps

What you'll learn?

  • Configure android project such as gradle and manifest file
  • Creating Firebase Project & do configuration
  • Writing code for push notification
  • Receive push notification
  • Send Push Notification via firebase console & curl

Firebase Cloud Messaging for Flutter

A Flutter plugin to use the Firebase Cloud Messaging (FCM) API.

With this plugin, your Flutter app can receive and process push notifications as well as data messages on Android and iOS. Read Firebase's About FCM Messages to learn more about the differences between notification messages and data messages.

1. Depend on it
Add this to your package's pubspec.yaml file:

dependencies:
  firebase_messaging: ^5.1.8

2. Install it
You can install packages from the command line:

with Flutter:

flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it
Now in your Dart code, you can use:

import 'package:firebase_messaging/firebase_messaging.dart';

Getting Started

Check out the example directory for a sample app using Firebase Cloud Messaging.

Android Integration #

To integrate your plugin into the Android part of your app, follow these steps:

Using the Firebase Console add an Android app to your project: Follow the assistant, download the generated google-services.json file and place it inside android/app.

Add the classpath to the [project]/android/build.gradle file.

dependencies {
  // Example existing classpath
  classpath 'com.android.tools.build:gradle:3.2.1'
  // Add the google services classpath
  classpath 'com.google.gms:google-services:4.3.0'
}

Add the apply plugin to the [project]/android/app/build.gradle file.

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

Note: If this section is not completed you will get an error like this:

java.lang.IllegalStateException:
Default FirebaseApp is not initialized in this process [package name].
Make sure to call FirebaseApp.initializeApp(Context) first.

Note: When you are debugging on Android, use a device or AVD with Google Play services. Otherwise you will not be able to authenticate.

  1. (optional, but recommended) If want to be notified in your app (via onResume and onLaunch, see below) when the user clicks on a notification in the system tray include the following intent-filter within the <activity> tag of your android/app/src/main/AndroidManifest.xml:
  intent-filter>
      action android:name="FLUTTER_NOTIFICATION_CLICK" />
      category android:name="android.intent.category.DEFAULT" />
  intent-filter>

Optionally handle background messages #

Background message handling is intended to be performed quickly. Do not perform long running tasks as they may not be allowed to finish by the Android system. See Background Execution Limits for more.

By default background messaging is not enabled. To handle messages in the background:

1. Add an Application.java class to your app

 package io.flutter.plugins.firebasemessagingexample;

 import io.flutter.app.FlutterApplication;
 import io.flutter.plugin.common.PluginRegistry;
 import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
 import io.flutter.plugins.GeneratedPluginRegistrant;
 import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;

 public class Application extends FlutterApplication implements PluginRegistrantCallback {
   @Override
   public void onCreate() {
     super.onCreate();
     FlutterFirebaseMessagingService.setPluginRegistrant(this);
   }

   @Override
   public void registerWith(PluginRegistry registry) {
     GeneratedPluginRegistrant.registerWith(registry);
   }
 }

2. Set name property of application in AndroidManifest.xml

 <application android:name=".Application" ...>

3. Define a top level Dart method to handle background messages

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
  if (message.containsKey('data')) {
    // Handle data message
    final dynamic data = message['data'];
  }

  if (message.containsKey('notification')) {
    // Handle notification message
    final dynamic notification = message['notification'];
  }

  // Or do other work.
}

Note: the protocol of data and notification are in line with the fields defined by a RemoteMessage.

  1. Set onBackgroundMessage handler when calling configure
_firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        _navigateToItemDetail(message);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        _navigateToItemDetail(message);
      },
    );

Note: configure should be called early in the lifecycle of your application so that it can be ready to receive messages as early as possible. See the example app for a demonstration.

iOS Integration #

To integrate your plugin into the iOS part of your app, follow these steps:

1.Generate the certificates required by Apple for receiving push notifications following this guide in the Firebase docs. You can skip the section titled "Create the Provisioning Profile".

  1. Using the Firebase Console add an iOS app to your project: Follow the assistant, download the generated GoogleService-Info.plist file, open ios/Runner.xcworkspace with Xcode, and within Xcode place the file inside ios/Runner. Don't follow the steps named "Add Firebase SDK" and "Add initialization code" in the Firebase assistant.
  2. In Xcode, select Runner in the Project Navigator. In the Capabilities Tab turn on Push Notifications and Background Modes, and enable Background fetch and Remote notifications under Background Modes.
  3. Follow the steps in the "Upload your APNs certificate" section of the Firebase docs.

Dart/Flutter Integration #

From your Dart code, you need to import the plugin and instantiate it:

import 'package:firebase_messaging/firebase_messaging.dart';

final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

Next, you should probably request permissions for receiving Push Notifications. For this, call _firebaseMessaging.requestNotificationPermissions(). This will bring up a permissions dialog for the user to confirm on iOS. It's a no-op on Android. Last, but not least, register onMessage, onResume, and onLaunch callbacks via _firebaseMessaging.configure() to listen for incoming messages (see table below for more information).

Receiving Messages #

Messages are sent to your Flutter app via the onMessage, onLaunch, and onResume callbacks that you configured with the plugin during setup. Here is how different message types are delivered on the supported platforms:
App in ForegroundApp in BackgroundApp TerminatedNotification on AndroidonMessageNotification is delivered to system tray. When the user clicks on it to open app onResume fires if click_action: FLUTTER_NOTIFICATION_CLICK is set (see below).Notification is delivered to system tray. When the user clicks on it to open app onLaunch fires if click_action: FLUTTER_NOTIFICATION_CLICK is set (see below).Notification on iOSonMessageNotification is delivered to system tray. When the user clicks on it to open app onResume fires.Notification is delivered to system tray. When the user clicks on it to open app onLaunch fires.Data Message on AndroidonMessage``````onMessage while app stays in the background.not supported by plugin, message is lostData Message on iOSonMessageMessage is stored by FCM and delivered to app via onMessage when the app is brought back to foreground.Message is stored by FCM and delivered to app via onMessage when the app is brought back to foreground.

Additional reading: Firebase's About FCM Messages.

Notification messages with additional data #

It is possible to include additional data in notification messages by adding them to the "data"-field of the message.

On Android, the message contains an additional field data containing the data. On iOS, the data is directly appended to the message and the additional data-field is omitted.

To receive the data on both platforms:

Futurevoid> _handleNotification (Mapdynamic, dynamic> message, bool dialog) async {
    var data = message['data'] ?? message;
    String expectedAttribute = data['expectedAttribute'];
    /// [...]
}

Sending Messages #

Refer to the Firebase documentation about FCM for all the details about sending messages to your app. When sending a notification message to an Android device, you need to make sure to set the click_action property of the message to FLUTTER_NOTIFICATION_CLICK. Otherwise the plugin will be unable to deliver the notification to your app when the users clicks on it in the system tray.

For testing purposes, the simplest way to send a notification is via the Firebase Console. Make sure to include click_action: FLUTTER_NOTIFICATION_CLICK as a "Custom data" key-value-pair (under "Advanced options") when targeting an Android device. The Firebase Console does not support sending data messages.

Alternatively, a notification or data message can be sent from a terminal:

DATA='{"notification": {"body": "this is a body","title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "<FCM TOKEN>"}'
curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=<FCM SERVER KEY>"

Remove the notification property in DATA to send a data message.