0
0
Firebasecloud~7 mins

Authentication trigger functions in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Authentication trigger functions run automatically when users sign up or log in. They help you react to these events, like sending welcome messages or updating user data.
When you want to send a welcome email right after a user creates an account.
When you need to log user sign-in times for analytics.
When you want to update user profiles in your database after they sign up.
When you want to block or flag suspicious sign-ins automatically.
When you want to customize user experience based on their login events.
Config File - index.js
index.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Triggered when a user signs up
exports.onUserCreate = functions.auth.user().onCreate((user) => {
  console.log('New user created:', user.uid);
  // Example: Add user data to Firestore
  return admin.firestore().collection('users').doc(user.uid).set({
    email: user.email,
    createdAt: admin.firestore.FieldValue.serverTimestamp()
  });
});

// Triggered when a user deletes their account
exports.onUserDelete = functions.auth.user().onDelete((user) => {
  console.log('User deleted:', user.uid);
  // Example: Remove user data from Firestore
  return admin.firestore().collection('users').doc(user.uid).delete();
});

This file defines two Firebase Authentication trigger functions.

  • onUserCreate: Runs when a new user signs up. It logs the user ID and saves user info in Firestore.
  • onUserDelete: Runs when a user deletes their account. It logs the user ID and removes their data from Firestore.

This setup helps keep your database in sync with user authentication events.

Commands
Deploys the authentication trigger functions to Firebase so they run automatically on user events.
Terminal
firebase deploy --only functions
Expected OutputExpected
=== Deploying to 'your-project-id'... i deploying functions Running command: npm --prefix "$RESOURCE_DIR" run lint > functions@ lint /workspace/functions > eslint . ✔ functions: Finished running lint. ✔ functions: Using node@16 ✔ functions: Finished deployment. Project Console: https://console.firebase.google.com/project/your-project-id/overview ✔ Deploy complete!
--only - Deploy only the specified Firebase feature, here 'functions' to avoid deploying other resources.
Shows logs from your deployed functions to verify they run correctly when triggered.
Terminal
firebase functions:log
Expected OutputExpected
2024-06-01T12:00:00.000Z onUserCreate: New user created: abc123def456 2024-06-01T12:05:00.000Z onUserDelete: User deleted: abc123def456
Imports users into Firebase Authentication, which can trigger the onUserCreate function if new users are added.
Terminal
firebase auth:import users.json --hash-algo=SCRYPT --hash-key=base64encodedkey
Expected OutputExpected
Importing users... Successfully imported 3 users.
--hash-algo - Specifies the password hashing algorithm used in the import file.
--hash-key - Provides the key used for password hashing in base64 format.
Key Concept

If you remember nothing else from this pattern, remember: authentication trigger functions run automatically on user sign-up or deletion to keep your app data updated.

Common Mistakes
Not initializing the Firebase Admin SDK before using Firestore in the function.
Without initialization, the function cannot access Firestore and will fail.
Always call admin.initializeApp() at the start of your functions file.
Deploying functions without the --only flag and accidentally deploying other Firebase resources.
This can cause unintended changes or longer deployment times.
Use 'firebase deploy --only functions' to deploy only your functions.
Not checking function logs after deployment to verify triggers work.
You might miss errors or failures in your functions.
Use 'firebase functions:log' to monitor function execution and debug.
Summary
Write authentication trigger functions to run code when users sign up or delete accounts.
Deploy functions using 'firebase deploy --only functions' to update your cloud triggers.
Check function logs with 'firebase functions:log' to ensure your triggers run correctly.