0

I am trying to create a firebase function that essentially listens to an event where a user created using the firebase authentication and then it creates a new record in the real time database where the user ID is the record itself and it also has a permission value set to false

in run into errors when deploying, someone can help?

when I run

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

const addUserToDatabase  = (userRecord) => {
    const uid = userRecord.uid;
    const email = userRecord.email;
  
    return admin.database().ref(`/Users/${uid}`).set({
      email: email,
      permission: false
    });
  }

// This function runs when a new user is created via Firebase Authentication

module.exports = {
    addUserToDatabase: functions.auth.user().onCreate(addUserToDatabase),
  }
  

I get this error

    TypeError: Cannot read properties of undefined (reading 'user')
        at Object.<anonymous> (/Users/yanir/coding/fBCLI/functions/index.js:19:39)
        at Module._compile (node:internal/modules/cjs/loader:1554:14)
        at Object..js (node:internal/modules/cjs/loader:1706:10)
        at Module.load (node:internal/modules/cjs/loader:1289:32)
        at Function._load (node:internal/modules/cjs/loader:1108:12)
        at TracingChannel.traceSync (node:diagnostics_channel:322:14)
        at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
        at Module.require (node:internal/modules/cjs/loader:1311:12)
        at require (node:internal/modules/helpers:136:16)
        at loadModule (/Users/yanir/coding/fBCLI/functions/node_modules/firebase-functions/lib/runtime/loader.js:40:16)

package.json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "22"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^12.6.0",
    "firebase-functions": "^6.3.2"
  },
  "devDependencies": {
    "firebase-functions-test": "^3.1.0"
  },
  "private": true
}

1 Answer 1

1

The API changed in version 6 of firebase-functions with the addition of gen2 APIs for most other types of triggers (except auth, which is still on gen1). Your require statement should look like this now:

const functions = require("firebase-functions/v1");

You can see a more complete example of an auth trigger on GitHub.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.