Firebase-functions: functions.auth.user().onCreate is not triggering on new Firebase Authentication user.

Created on 16 Dec 2019  Â·  22Comments  Â·  Source: firebase/firebase-functions

Firebase functions version 3.3.0

Node version v10.13.0

Firebase version 7.10.0

Create a cloud function with firebase auth user onCreate trigger, it does not trigger at all, expecting it to trigger on creation of a new auth user and run my cloud function.

The function deploys correctly but does not fire.

Attention auth bug

Most helpful comment

  1. Do you mind sharing your steps / code to reproduce this?
  2. What region is your function deployed to? We have an internal issue being tracked that's affecting europe-west1 region. (internal tracking: 145502073)

I'm experiencing the same on us-central1.

export const createProfile = functions.auth.user().onCreate((user) => {
    return admin.firestore().collection('users').doc(user.uid).set({
    });
});

The just firebase deploy --only functions

Deployment is successful but it never gets triggered.
I'm testing it with the same account that I delete from firebase.

Hope that helps.

All 22 comments

I found a few problems with this issue:

  • I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
  • This issue does not have all the information required by the template. Looks like you forgot to fill out some sections. Please update the issue with more information.

Hello, thanks for submitting your issue. Can you please provide answers to all the required questions? Thanks!

Updated my original comment with answers to the required questions :)

@jamie-chapman

  1. Do you mind sharing your steps / code to reproduce this?
  2. What region is your function deployed to? We have an internal issue being tracked that's affecting europe-west1 region. (internal tracking: 145502073)

Thanks!

  1. Do you mind sharing your steps / code to reproduce this?
  2. What region is your function deployed to? We have an internal issue being tracked that's affecting europe-west1 region. (internal tracking: 145502073)

I'm experiencing the same on us-central1.

export const createProfile = functions.auth.user().onCreate((user) => {
    return admin.firestore().collection('users').doc(user.uid).set({
    });
});

The just firebase deploy --only functions

Deployment is successful but it never gets triggered.
I'm testing it with the same account that I delete from firebase.

Hope that helps.


Hey @jamie-chapman. We need more information to resolve this issue but there hasn't been an update in 7 days. I'm marking the issue as stale and if there are no new updates in the next 3 days I will close it automatically.

If you have more information that will help us get to the bottom of this, just add a comment!

What more information is needed?

Hello, we are still working to fix the issue for US central 1. We'll update you with more progress on our end

Hi, i'm facing a similar issue, the function is executed, but sometimes the users collection is updated and sometimes not, i'm using in front the follow function:

Front work

export const signUp = newUser => {
  return (dispatch, getState, { getFirebase, getFirestore }) => {
    const firestore = getFirestore();
    firebase
      .createUser(
        {
          email: newUser.email,
          password: newUser.password
        },
        {
          firstName: newUser.firstName,
          lastName: newUser.lastName,
        }
      )
      .then(_ => {      
        const user = firebase.auth().currentUser;  

        if (user) {
          firestore
            .collection("users")
            .doc(user.uid)
            .update({
              userId: user.uid
            })
            .then(_ => {
              dispatch({ type: "SIGNUP_SUCCESS" });
            });
        }

      })
      .catch(err => {
        dispatch({ type: "SIGNUP_ERROR", err });
      });
  };
};

In cloud functions sometimes work:

export default functions.auth.user().onCreate(async (user) => {
  const customer = await stripe.customers.create({ email: user.email });
  return await 
      admin
        .firestore()
        .collection("users")
        .doc(user.uid)
        .update({
          customer_id: customer.id
        });
});

I don't know if is a code issue or a cloud firestore issue, thanks!

I'm also seeing intermittent failures on two functions performing Firestore add() operations.

7.5.0/firebase-app.js
7.5.0/firebase-auth.js
7.5.0/firebase-firestore.js
7.5.0/firebase-functions.js

About 2 minutes after a failed invocation I receive two log message:

1:
Unhandled rejection

2:

Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
    at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/google-auth-library/build/src/auth/googleauth.js:159:19)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

Both functions running in Region us-central1

Cloud Firestore location: nam5 (us-central)

I am also having problems with the onCreate trigger. It is not been called. Here is my code:

exports.myFunction = functions.database.ref('/collection/{id}').onCreate((snapshot, context) => {
  const a= snapshot.val();
  return admin.firestore().doc('other/'+o.id).set({
    // data...
  }).then(function () {
    console.log('Successfully created other');
  }).catch(function (error) {
    console.log('Error creating other:', error);
  });
});

Hello, thanks for submitting your issue. Can you please provide answers to all the required questions? Thanks!

Hi, so it's

@jamie-chapman

  1. Do you mind sharing your steps / code to reproduce this?
  2. What region is your function deployed to? We have an internal issue being tracked that's affecting europe-west1 region. (internal tracking: 145502073)

Thanks!

Hi,

So steps to reproduce would be to create a function that triggers with Firebase Authentication. The region is europe-west1.

To anybody experiencing this issue, here is the solution:

The reason you cannot do something like

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  return await admin
    .firestore()
    .collection("users")
    .set({ user })
})

is because the user object causes an error - you can see this in the Firebase dashboard at Functions > Logs

Couldn't serialize object of type "UserRecordMetadata" (found in field "metadata"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

Instead something like this will work:

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  const { uid, displayName, email } = user

  return await admin
    .firestore()
    .collection("users")
    .doc(uid)
    .set({ uid, displayName, email })
})

We essentially just extract the uid, displayName, email fields off of the user and use only those ones to create the new user document, thereby avoiding the object inside user.metadata

To anybody experiencing this issue, here is the solution:

The reason you cannot do something like

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  return await admin
    .firestore()
    .collection("users")
    .set({ user })
})

is because the user object causes an error - you can see this in the Firebase dashboard at Functions > Logs

Couldn't serialize object of type "UserRecordMetadata" (found in field "metadata"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

Instead something like this will work:

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  const { uid, displayName, email } = user

  return await admin
    .firestore()
    .collection("users")
    .doc(uid)
    .set({ uid, displayName, email })
})

We essentially just extract the uid, displayName, email fields off of the user and use only those ones to create the new user document, thereby avoiding the object inside user.metadata

This is about wrong implementation.
The issue is that the function just isn't called. If I put in just a print() nothing happens

EDIT:
My bad,..
For me this wasn't a bug... The doc states:

A Cloud Functions event is not triggered when a user signs in for the first time using a custom token.

And thats exactly what I'm using...
So I need to find another way to handle the creation of a user profile..

Why is a custom token not supported?

@jamie-chapman Sorry for the delay - we need your project name, region and function name of a function with a recent failure. In order to trace the failure, it needs to be recent since the server logs deletes them after a while

@andrianabeltran Hi, sorry I cannot be of more help but this hasn't happened to me for some months now. Perhaps someone else on this thread has however?

I am seeing the same here by just following the code in the firebase docs: https://firebase.google.com/docs/auth/admin/custom-claims

I create the user and the functions trigger never gets called.

I"m also experiencing this, it seems to be limited to social auth, I'm only using google, while email and phone auth seem to be fine.

This issue is best served by contacting Firebase support -- if a function
is deployed but not triggering that's an issue in the backend and not
something that can be addressed in the SDK.

On Fri, Apr 3, 2020, 6:12 PM Paul notifications@github.com wrote:

I"m also experiencing this, it seems to be limited to social auth, I'm
only using google, while email and phone auth seem to be fine.

—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/firebase/firebase-functions/issues/595#issuecomment-608948299,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AAAAH7UUSHG6QJ26K4SILELRK2CRRANCNFSM4J3NMCIA
.

To anybody experiencing this issue, here is the solution:
The reason you cannot do something like

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  return await admin
    .firestore()
    .collection("users")
    .set({ user })
})

is because the user object causes an error - you can see this in the Firebase dashboard at Functions > Logs

Couldn't serialize object of type "UserRecordMetadata" (found in field "metadata"). Firestore doesn't support JavaScript objects with custom prototypes (i.e. objects that were created via the "new" operator).

Instead something like this will work:

exports.handleNewSignups = functions.auth.user().onCreate(async user => {
  const { uid, displayName, email } = user

  return await admin
    .firestore()
    .collection("users")
    .doc(uid)
    .set({ uid, displayName, email })
})

We essentially just extract the uid, displayName, email fields off of the user and use only those ones to create the new user document, thereby avoiding the object inside user.metadata

This is about wrong implementation.
The issue is that the function just isn't called. If I put in just a print() nothing happens

Actually there is a way to save the whole Object without losing some info.
That's how I ended up implementing it:

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

exports.saveNewUser = functions.auth.user().onCreate(async user => {
    return admin
    .firestore()
    .collection('users')
    .doc(user.uid)
    .set(JSON.parse(JSON.stringify(user)));
  })

@aner87 solution solved my problem using firebase auth onCreate trigger with cloud functions. thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

OxyFlax picture OxyFlax  Â·  33Comments

agordeev picture agordeev  Â·  43Comments

iouhammi picture iouhammi  Â·  24Comments

brianmhunt picture brianmhunt  Â·  47Comments

peterpeterparker picture peterpeterparker  Â·  53Comments