Cloud Functions by Firebase vs Cloud Functions

November 17, 2020

Cloud Functions by Firebase

https://firebase.google.com/docs/functions

  • Support Node.js only
  • Good support for local machine testing using Firebase emulators (Cloud Functions, Cloud Firestore, Cloud Authentication, etc)

Simple HTTP function

const functions = require('firebase-functions');

exports.hello = functions.https.onRequest((req, res) => {
  res.send(`Hello ${req.query.name}`);
});

Deploy

firebase deploy --only functions:hello

Functions triggered by Google Authentication (when new user is created)

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.initUser = functions.auth.user().onCreate(async (user) => {
  let docRef = db.collection('user').doc(user.uid);

  await docRef.set({
    created: admin.firestore.Timestamp.now(), // user.metadata.createdAt
    name: user.displayName,
    email: user.email
  });
});
firebase deploy --only functions:initUser

Cloud Functions

https://cloud.google.com/functions

  • Support Node.js, Python, Go, Java, .NET

Simple HTTP function

exports.hello = (req, res) => {
  res.send(`Hello ${req.query.name}`);
};

Deploy

gcloud functions deploy hello --runtime nodejs10 --trigger-http --allow-unauthenticated

Functions triggered by Google Authentication (when new user is created)

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.initUser = async (event) => {
  let docRef = db.collection('user').doc(event.uid);

  await docRef.set({
    created: admin.firestore.Timestamp.now(), // event.metadata.createdAt
    name: event.displayName,
    email: event.email
  });
};

Deploy

gcloud functions deploy initUser --trigger-event providers/firebase.auth/eventTypes/user.create --runtime nodejs10
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.