Firebase Cloud Function (Node.js) Write to Firestore Upon Firebase Authentication User Signup

November 17, 2020

Note

I am using Cloud Functions for Firebase instead of Cloud Functions. Reason being I enjoy the testability on local machine using Firebase.

NOTE: Cloud Functions by Firebase vs Cloud Functions.

Setup

Setup Firebase Project

mkdir PROJECT_NAME
cd PROJECT_NAME

firebase init

with the following selected

❯◯ Database: Deploy Firebase Realtime Database Rules
 ◉ Firestore: Deploy rules and create indexes for Firestore
 ◉ Functions: Configure and deploy Cloud Functions
 ◉ Hosting: Configure and deploy Firebase Hosting sites
 ◯ Storage: Deploy Cloud Storage security rules
 ◉ Emulators: Set up local emulators for Firebase features
 ◯ Remote Config: Get, deploy, and rollback configurations for Remote Config

You need the following emulator if you want to test Authentication trigger on local machine

=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select emulator
s, then Enter to confirm your choices. 
 ◉ Authentication Emulator
 ◉ Functions Emulator
 ◉ Firestore Emulator
 ◯ Database Emulator
 ◉ Hosting Emulator
❯◯ Pub/Sub Emulator

NOTE: Select the options which enable Web UI for emulators as well

Cloud Functions

Edit functions/initUser.js

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

const db = admin.firestore();

// https://firebase.google.com/docs/functions/auth-events
exports.initUser = functions.auth.user().onCreate(async (user) => {

  let docRef = db.collection('user').doc(user.uid);

  const batch = db.batch();

  /*
  await docRef.set({
    created: admin.firestore.Timestamp.now(),
    name: user.displayName,
    active: false
  });
   */

  batch.set(docRef, {
    created: admin.firestore.Timestamp.now(),
    name: user.displayName,
    active: false
  });

  docRef = db.collection('user_private').doc(user.uid);

  batch.set(docRef, {
    email: user.email,
  });

  await batch.commit();
});

Edit functions/index.js

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

/*
exports.hello = functions.https.onRequest((req, res) => {
  res.send("Hello!");
});
 */

const initUser = require('./initUser');

exports.initUser = initUser.initUser

Deploy

firebase deploy --only functions:initUser

Test on Server

Goto https://console.cloud.google.com/functions/list

  • Click on Actions on initUser and select Test Function
  • Triggering event: {"uid": "test-1", "displayName": "Test 01", "email": "test@web.app"}
  • Click Test the Function

NOTE: This testing run on life production, so you might want to delete the created entry in Firestore.

Test on Local Machine with Emulators

Test Firebase Authentication Cloud Functions Trigger on Local Machine With Emulators

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.