How to Trigger Function on Auth Create in Firebase
Use Firebase Cloud Functions with the
functions.auth.user().onCreate trigger to run code automatically when a new user signs up. This function listens for new user creation events in Firebase Authentication and executes your custom logic.Syntax
The functions.auth.user().onCreate method sets up a trigger that runs your function whenever a new user account is created in Firebase Authentication.
functions.auth.user(): Accesses the authentication user event triggers..onCreate(callback): Registers a callback function to run when a user is created.callback(user): The function that receives the new user data.
javascript
const functions = require('firebase-functions'); exports.onUserCreate = functions.auth.user().onCreate((user) => { // Your code here });
Example
This example shows a Firebase Cloud Function that triggers when a new user signs up. It logs the user's email and UID to the console.
javascript
const functions = require('firebase-functions'); exports.welcomeNewUser = functions.auth.user().onCreate((user) => { console.log(`New user created: ${user.email} (UID: ${user.uid})`); // Additional logic like sending welcome email can be added here });
Output
New user created: user@example.com (UID: abc123def456)
Common Pitfalls
Common mistakes when using onCreate triggers include:
- Not deploying the function after writing it, so it doesn't run.
- Trying to use
onCreateon other Firebase services instead offunctions.auth.user(). - Not handling asynchronous code properly inside the callback, which can cause unexpected behavior.
- Assuming the function triggers on user sign-in instead of user creation.
javascript
/* Wrong: Using onCreate on Firestore instead of Auth */ exports.wrongTrigger = functions.firestore.document('users/{userId}').onCreate((snap, context) => { // This triggers on Firestore document creation, not auth user creation }); /* Right: Using onCreate on Auth user */ exports.correctTrigger = functions.auth.user().onCreate((user) => { // Correct trigger for new auth users });
Quick Reference
Remember these key points when triggering functions on auth create:
- Use
functions.auth.user().onCreateto listen for new user sign-ups. - The callback receives a
userobject with user details. - Deploy your function with
firebase deploy --only functionsto activate it. - Use asynchronous code carefully inside the callback.
Key Takeaways
Use functions.auth.user().onCreate to trigger code when a new Firebase user is created.
The callback function receives the new user's data for custom processing.
Always deploy your Cloud Functions after writing or updating them.
Do not confuse auth triggers with Firestore or other service triggers.
Handle asynchronous operations properly inside the trigger function.