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

November 17, 2020


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 Firebase Project


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');

const db = admin.firestore();

exports.initUser = functions.auth.user().onCreate(async (user) => {

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

  const batch = db.batch();

  await docRef.set({
    name: user.displayName,
    active: false

  batch.set(docRef, {
    name: user.displayName,
    active: false

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

  batch.set(docRef, {

  await batch.commit();

Edit functions/index.js

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

exports.hello = functions.https.onRequest((req, res) => {

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

exports.initUser = initUser.initUser


firebase deploy --only functions:initUser

Test on Server


  • Click on Actions on initUser and select Test Function
  • Triggering event: {"uid": "test-1", "displayName": "Test 01", "email": ""}
  • 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


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