You can trigger functions in response to the creation and deletion of Firebase Authentication user accounts. For example, you could send a welcome email to a user who has just created an account in your app. Examples on this page are based on a sample that does exactly this—sends welcome and farewell emails upon account creation and deletion.
For more examples of use cases, see What can I do with Cloud Functions?.
Trigger a function on user creation
You can create a function that triggers when an Authentication user is created using
the
onUserCreated
event handler from the firebase-functions/v2/identity subpackage in Node.js,
or the
@identity_fn.on_user_created
decorator from firebase_functions.identity_fn in Python:
Node.js
const { onUserCreated } = require("firebase-functions/identity"); const { defineSecret } = require("firebase-functions/params"); const { logger } = require("firebase-functions"); const { sendWelcomeEmail } = require("./utils/myEmailService"); const emailApiKey = defineSecret("EMAIL_API_KEY"); exports.newUserWelcome = onUserCreated( { secrets: [emailApiKey] }, async (event) => { const { uid, email, displayName } = event.data; if (!email) { logger.log(`User ${uid} does not have an email address.`); return; } await sendWelcomeEmail(email, displayName); }, );
Python
from firebase_functions import identity_fn, logger
@identity_fn.on_user_created()
def on_create_all(event: identity_fn.AuthEvent) -> None:
user = event.data
logger.info(
f"New user created: uid={user.uid} email={user.email}"
)
Authentication accounts will trigger user creation events for Cloud Functions when:
- A user creates an email account and password.
- A user signs in for the first time using a federated identity provider.
- The developer creates an account using the Admin SDK.
- A user signs in to a new anonymous auth session for the first time.
A Cloud Functions event is not triggered when a user signs in for the first time using a custom token.
Configure trigger options and multi-tenancy
You can configure your function by passing an options object (AuthOptions) as
the first parameter to onUserCreated in Node.js, or by passing keyword
arguments to @identity_fn.on_user_created in Python:
Node.js
/** * Sends a welcome email scoped to a specific tenant in Identity Platform. */ exports.sendWelcomeEmailToTenant = onUserCreated( { secrets: [emailApiKey], // Only trigger when a user is a member of this tenant tenantId: "my-tenant-id", }, async (event) => { const { uid, email, displayName } = event.data; // Customize the email for this tenant await sendWelcomeEmail(email, displayName, event.tenantId); }, ); /** * Sends a welcome email only to users not associated with any tenant. */ exports.sendWelcomeEmailNoTenant = onUserCreated( { secrets: [emailApiKey], // Only trigger when a user is NOT a member of a tenant tenantId: IS_NOT_TENANT, }, async (event) => { const { email, displayName } = event.data; // Send a generic welcome email await sendWelcomeEmail(email, displayName); }, );
Python
from firebase_functions import identity_fn, logger
# Use the tenant ID, not the tenant's display name
TENANT_ID = "TENANT_ID"
# Default project only (ignore tenant users)
@identity_fn.on_user_created(tenant_id=identity_fn.IS_NOT_TENANT)
def on_create_no_tenant(event: identity_fn.AuthEvent) -> None:
logger.info(f"Default project user created: uid={event.data.uid}")
# Specific tenant only
@identity_fn.on_user_created(tenant_id=TENANT_ID)
def on_create_tenant(event: identity_fn.AuthEvent) -> None:
logger.info(
f"Tenant user created: uid={event.data.uid} "
f"tenant={event.tenant_id}"
)
If your project uses Identity Platform multi-tenancy,
you can scope the trigger using tenantId (Node.js) or tenant_id (Python):
- Default project (no tenant): Set
tenantId(tenant_idin Python) toIS_NOT_TENANT(identity_fn.IS_NOT_TENANTin Python) to listen only for users created in the default project and ignore tenant users. Specific tenant: Provide the full string ID of the tenant (for example,
{ tenantId: "tenant-id-1" }in Node.js ortenant_id="my-tenant-sl5r1"in Python) to listen only for users created in that tenant. You can also pass a parameterized value (defineStringin Node.js,params.StringParamin Python):from firebase_functions import identity_fn, logger, params TENANT_PARAM = params.StringParam("TENANT_ID") @identity_fn.on_user_created(tenant_id=TENANT_PARAM) def on_create_param_tenant(event: identity_fn.AuthEvent) -> None: logger.info( f"Parameterized tenant user created: uid={event.data.uid} " f"tenant={event.tenant_id}" )All tenants and users: If
tenantId(tenant_idin Python) is omitted, the function triggers on user creation events across all tenants and default project users in the project.
In addition to tenantId (tenant_id in Python), you can specify standard 2nd
gen configuration options including region, concurrency, cpu, memory,
timeoutSeconds (timeout_sec in Python), minInstances (min_instances in
Python), maxInstances (max_instances in Python), and secrets.
Access user attributes
From the user data returned to your function, you can access the list of user
attributes available in the newly created user's
UserRecord
(AuthUserRecord
in Python) object using event.data. For example, you can get the user's email
and display name as shown:
Node.js
const { uid, email, displayName } = event.data;
Python
from firebase_functions import identity_fn, logger
@identity_fn.on_user_created()
def log_user_attributes(event: identity_fn.AuthEvent) -> None:
user = event.data
providers = [p.provider_id for p in user.provider_data]
logger.info(
f"uid={user.uid} email={user.email} tenant={event.tenant_id} "
f"created={user.metadata.creation_time} providers={providers}"
)
logger.info(f"Event Subject: {event.subject}")
Authentication triggers in 2nd gen receive an
AuthEvent
object. In addition to event.data, you can access event metadata such as:
event.id: A unique identifier for the event.event.type: The event type (such asgoogle.firebase.auth.user.v2.createdorgoogle.firebase.auth.user.v2.deleted).event.time: The timestamp representing when the event occurred (an ISO 8601 string in Node.js, or adatetimeobject in Python).event.subject: The resource subject that the event relates to.event.project: The Google Cloud project ID.event.tenantId(Node.js) /event.tenant_id(Python): The Identity Platform tenant ID associated with the user, if applicable.
Trigger a function on user deletion
Just as you can trigger a function on user creation, you can respond to user
deletion events. Use the
onUserDeleted
event handler from firebase-functions/v2/identity in Node.js, or the
@identity_fn.on_user_deleted
decorator from firebase_functions.identity_fn in Python:
Node.js
const { onUserDeleted } = require("firebase-functions/identity"); const { defineSecret } = require("firebase-functions/params"); const { logger } = require("firebase-functions"); const { sendGoodbyeEmail } = require("./utils/myEmailService"); const emailApiKey = defineSecret("EMAIL_API_KEY"); exports.deletedUserFarewell = onUserDeleted( { secrets: [emailApiKey] }, async (event) => { const { uid, email, displayName } = event.data; if (!email) { logger.log(`User ${uid} does not have an email address.`); return; } await sendGoodbyeEmail(email, displayName); }, );
Python
from firebase_functions import identity_fn, logger
# All users (default project and all tenants)
@identity_fn.on_user_deleted()
def on_delete_all(event: identity_fn.AuthEvent) -> None:
user = event.data
logger.info(
f"User deleted: uid={user.uid} email={user.email} "
f"tenant={event.tenant_id}"
)
# Default project only (ignore tenant users)
@identity_fn.on_user_deleted(tenant_id=identity_fn.IS_NOT_TENANT)
def on_delete_no_tenant(event: identity_fn.AuthEvent) -> None:
logger.info(f"Default project user deleted: uid={event.data.uid}")
# Specific tenant only
@identity_fn.on_user_deleted(tenant_id="TENANT_ID")
def on_delete_tenant(event: identity_fn.AuthEvent) -> None:
logger.info(
f"Tenant user deleted: uid={event.data.uid} "
f"tenant={event.tenant_id}"
)
As with onUserCreated (on_user_created in Python), you can configure
onUserDeleted (on_user_deleted in Python) with options like
{ tenantId: IS_NOT_TENANT } (tenant_id=identity_fn.IS_NOT_TENANT in Python)
to restrict triggers to users in the default project.
Trigger blocking functions
If you've upgraded to Firebase Authentication with Identity Platform, you can extend Firebase Authentication using blocking functions.
Blocking functions let you execute custom code synchronously that modifies the result of a user registering or signing in to your app. Unlike background triggers, which run asynchronously after an event has finished, blocking functions let you prevent a user from authenticating if they don't meet certain criteria, or update a user's information and claims before returning it to your client app.
Best practices for 2nd gen triggers
When implementing 2nd gen authentication triggers, keep the following best practices in mind:
- Account for concurrency: Cloud Functions (2nd gen) instances process concurrent requests (defaulting to 80 concurrent requests when CPU ≥ 1). Ensure that your function doesn't rely on global mutable state between concurrent executions.
- Design for idempotency: Event delivery in 2nd gen is at-least-once using Eventarc. Ensure that your functions are idempotent; for example, verify that a welcome email hasn't already been sent or a database entry initialized before performing side effects.
- Scope multi-tenant functions: If your app uses Identity Platform
multi-tenancy, verify whether your functions should handle events across all
tenants or only specific ones. Use
IS_NOT_TENANT(tenantId: IS_NOT_TENANTin Node.js ortenant_id=identity_fn.IS_NOT_TENANTin Python) to prevent tenant users from triggering functions intended only for the primary project. - Manage regions and resource allocation: Specify the function location
(
region) to minimize network latency between your authentication provider and your function execution environment. - Use Firebase CLI v15.34.1 or later for local emulation: When testing
2nd gen Authentication triggers locally with the Firebase Local Emulator Suite, use
firebase-toolsversion15.34.1or later to ensure the Auth Emulator emits the 2nd gen CloudEvent payload format.