/** * Background Function triggered by a change to a Firebase Auth user object. * * @param {!Object} event The Cloud Functions event. */exports.helloAuth=event=>{try{console.log(`Function triggered by change to user: ${event.uid}`);console.log(`Created at: ${event.metadata.createdAt}`);if(event.email){console.log(`Email: ${event.email}`);}}catch(err){console.error(err);}};
Python
importjsondefhello_auth(data,context):"""Triggered by creation or deletion of a Firebase Auth user object. Args: data (dict): The event payload. context (google.cloud.functions.Context): Metadata for the event. """print("Function triggered by creation/deletion of user: %s"%data["uid"])print("Created at: %s"%data["metadata"]["createdAt"])if"email"indata:print("Email: %s"%data["email"])
Go
// Package firebase contains a Firestore Cloud Function.packagefirebaseimport("context""log""time")// AuthEvent is the payload of a Firestore Auth event.typeAuthEventstruct{Emailstring`json:"email"`Metadatastruct{CreatedAttime.Time`json:"createdAt"`}`json:"metadata"`UIDstring`json:"uid"`}// HelloAuth is triggered by Firestore Auth events.funcHelloAuth(ctxcontext.Context,eAuthEvent)error{log.Printf("Function triggered by creation or deletion of user: %q",e.UID)log.Printf("Created at: %v",e.Metadata.CreatedAt)ife.Email!=""{log.Printf("Email: %q",e.Email)}returnnil}
Java
importcom.google.cloud.functions.Context;importcom.google.cloud.functions.RawBackgroundFunction;importcom.google.gson.Gson;importcom.google.gson.JsonObject;importjava.util.logging.Logger;publicclassFirebaseAuthimplementsRawBackgroundFunction{privatestaticfinalLoggerlogger=Logger.getLogger(FirebaseAuth.class.getName());// Use GSON (https://github.com/google/gson) to parse JSON content.privatestaticfinalGsongson=newGson();@Overridepublicvoidaccept(Stringjson,Contextcontext){JsonObjectbody=gson.fromJson(json,JsonObject.class);if(body!=null && body.has("uid")){logger.info("Function triggered by change to user: "+body.get("uid").getAsString());}if(body!=null && body.has("metadata")){JsonObjectmetadata=body.get("metadata").getAsJsonObject();logger.info("Created at: "+metadata.get("createdAt").getAsString());}if(body!=null && body.has("email")){logger.info("Email: "+body.get("email").getAsString());}}}
C#
usingCloudNative.CloudEvents;usingGoogle.Cloud.Functions.Framework;usingGoogle.Events.Protobuf.Firebase.Auth.V1;usingMicrosoft.Extensions.Logging;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceFirebaseAuth;publicclassFunction:ICloudEventFunction<AuthEventData>{privatereadonlyILogger_logger;publicFunction(ILogger<Function>logger)=>
_logger=logger;publicTaskHandleAsync(CloudEventcloudEvent,AuthEventDatadata,CancellationTokencancellationToken){_logger.LogInformation("Function triggered by change to user: {uid}",data.Uid);if(data.MetadataisUserMetadatametadata){_logger.LogInformation("User created at: {created:s}",metadata.CreateTime.ToDateTimeOffset());}if(!string.IsNullOrEmpty(data.Email)){_logger.LogInformation("Email: {email}",data.Email);}// In this example, we don't need to perform any asynchronous operations, so the// method doesn't need to be declared async.returnTask.CompletedTask;}}
Ruby
require"functions_framework"# Triggered by creation or deletion of a Firebase Auth user object.FunctionsFramework.cloud_event"hello_auth"do|event|# Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.# See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html# The Firebase event payload can be obtained from the `data` field.payload=event.datalogger.info"Function triggered by creation/deletion of user: #{payload['uid']}"logger.info"Created at: #{payload['metadata']['createdAt']}"logger.info"Email: #{payload['email']}"ifpayload.key?"email"end
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-09-03。"],[[["\u003cp\u003eFirebase Authentication triggers Cloud Run functions in response to user creation and deletion events within the same Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eCloud Run functions are triggered when a user creates an account, signs in with a federated identity, an account is created with the Firebase Admin SDK, or when a user signs in to a new anonymous session.\u003c/p\u003e\n"],["\u003cp\u003eEvent data, provided as a \u003ccode\u003eUserRecord\u003c/code\u003e object, includes details like email, creation timestamp, and a unique user ID, although certain properties are dependent on the authentication method used.\u003c/p\u003e\n"],["\u003cp\u003eDeploying a function requires specifying the event type (\u003ccode\u003ecreate\u003c/code\u003e or \u003ccode\u003edelete\u003c/code\u003e) and the project ID, which can be done through the Google Cloud console or via the command line using specific strings.\u003c/p\u003e\n"],["\u003cp\u003eBeta triggers for Firebase Authentication are subject to change over time and may not be compatible between different versions of the pre-GA feature.\u003c/p\u003e\n"]]],[],null,["# Firebase Authentication Triggers\n================================\n\n|\n| **Beta**\n|\n|\n| This feature is covered by the\n| [Pre-GA Offerings Terms](/terms/service-terms#1) of the Google Cloud\n| Terms of Service. Pre-GA features may have limited support, and changes\n| to pre-GA features may not be compatible with other pre-GA versions.\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n|\n|\n| Specifically, note that\n| [CloudEvents](/functions/1stgendocs/writing/write-event-driven-functions) that are\n| generated by Beta triggers may change format over time. The `Source`\n| and `Subject` attributes, additional extension attributes, and the\n| data (payload) format are all subject to change.\n\n\u003cbr /\u003e\n\nCloud Run functions can be triggered by events from\n[Firebase Authentication](https://firebase.google.com/docs/auth/) in the same\nGoogle Cloud project as the function. These events include user creation and\nuser deletion. For example, you could send a welcome email to a user who has\njust created an account in your app.\n\nEvent types\n-----------\n\nFirebase Authentication can trigger functions in response to user `create` and\n`delete` events.\n\n### User creation\n\nFirebase accounts trigger user creation events for Cloud Run functions when:\n\n- A user creates an email account and password.\n\n- A user signs in for the first time using a federated identity provider.\n\n- The developer creates an account using the Firebase Admin SDK.\n\n- A user signs in to a new anonymous auth session for the first time.\n\n| **Note:** A Cloud Run functions event **is not** triggered when a user signs in for the first time using a custom token.\n\n### User deletion\n\nYou can also configure a function to trigger upon user deletion.\n\nEvent structure\n---------------\n\nEvent data is provided as a [`UserRecord` object](https://firebase.google.com/docs/reference/functions/firebase-functions.auth.userrecordmetadata).\n\nAn example [password-based account](https://firebase.google.com/docs/auth/web/password-auth) creation event is shown\nbelow: \n\n```bash\n{\n \"email\": \"me@example.com\",\n \"metadata\": {\n \"createdAt\": \"2018-10-19T19:29:16Z\"\n },\n \"uid\": \"XXXXX\"\n}\n```\n\nSome properties of this object are only defined when using certain\nauthentication methods. For example, [password-based account](https://firebase.google.com/docs/auth/web/password-auth)\nevents define an `email` property containing the user's email address. The `uid`\nproperty (which contains a user ID unique to your project) is always defined.\n\nSample code\n-----------\n\n### Node.js\n\n /**\n * Background Function triggered by a change to a Firebase Auth user object.\n *\n * @param {!Object} event The Cloud Functions event.\n */\n exports.helloAuth = event =\u003e {\n try {\n console.log(`Function triggered by change to user: ${event.uid}`);\n console.log(`Created at: ${event.metadata.createdAt}`);\n\n if (event.email) {\n console.log(`Email: ${event.email}`);\n }\n } catch (err) {\n console.error(err);\n }\n };\n\n### Python\n\n import json\n\n def hello_auth(data, context):\n \"\"\"Triggered by creation or deletion of a Firebase Auth user object.\n Args:\n data (dict): The event payload.\n context (google.cloud.functions.Context): Metadata for the event.\n \"\"\"\n print(\"Function triggered by creation/deletion of user: %s\" % data[\"uid\"])\n print(\"Created at: %s\" % data[\"metadata\"][\"createdAt\"])\n\n if \"email\" in data:\n print(\"Email: %s\" % data[\"email\"])\n\n### Go\n\n\n // Package firebase contains a Firestore Cloud Function.\n package firebase\n\n import (\n \t\"context\"\n \t\"log\"\n \t\"time\"\n )\n\n // AuthEvent is the payload of a Firestore Auth event.\n type AuthEvent struct {\n \tEmail string `json:\"email\"`\n \tMetadata struct {\n \t\tCreatedAt time.Time `json:\"createdAt\"`\n \t} `json:\"metadata\"`\n \tUID string `json:\"uid\"`\n }\n\n // HelloAuth is triggered by Firestore Auth events.\n func HelloAuth(ctx context.Context, e AuthEvent) error {\n \tlog.Printf(\"Function triggered by creation or deletion of user: %q\", e.UID)\n \tlog.Printf(\"Created at: %v\", e.Metadata.CreatedAt)\n \tif e.Email != \"\" {\n \t\tlog.Printf(\"Email: %q\", e.Email)\n \t}\n \treturn nil\n }\n\n### Java\n\n import com.google.cloud.functions.Context;\n import com.google.cloud.functions.RawBackgroundFunction;\n import com.google.gson.Gson;\n import com.google.gson.JsonObject;\n import java.util.logging.Logger;\n\n public class FirebaseAuth implements RawBackgroundFunction {\n private static final Logger logger = Logger.getLogger(FirebaseAuth.class.getName());\n\n // Use GSON (https://github.com/google/gson) to parse JSON content.\n private static final Gson gson = new Gson();\n\n @Override\n public void accept(String json, Context context) {\n JsonObject body = gson.fromJson(json, JsonObject.class);\n\n if (body != null && body.has(\"uid\")) {\n logger.info(\"Function triggered by change to user: \" + body.get(\"uid\").getAsString());\n }\n\n if (body != null && body.has(\"metadata\")) {\n JsonObject metadata = body.get(\"metadata\").getAsJsonObject();\n logger.info(\"Created at: \" + metadata.get(\"createdAt\").getAsString());\n }\n\n if (body != null && body.has(\"email\")) {\n logger.info(\"Email: \" + body.get(\"email\").getAsString());\n }\n }\n }\n\n### C#\n\n```c#\nusing CloudNative.CloudEvents;\nusing Google.Cloud.Functions.Framework;\nusing Google.Events.Protobuf.Firebase.Auth.V1;\nusing Microsoft.Extensions.Logging;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace FirebaseAuth;\n\npublic class Function : ICloudEventFunction\u003cAuthEventData\u003e\n{\n private readonly ILogger _logger;\n\n public Function(ILogger\u003cFunction\u003e logger) =\u003e\n _logger = logger;\n\n public Task HandleAsync(CloudEvent cloudEvent, AuthEventData data, CancellationToken cancellationToken)\n {\n _logger.LogInformation(\"Function triggered by change to user: {uid}\", data.Uid);\n if (data.Metadata is UserMetadata metadata)\n {\n _logger.LogInformation(\"User created at: {created:s}\", metadata.CreateTime.ToDateTimeOffset());\n }\n if (!string.IsNullOrEmpty(data.Email))\n {\n _logger.LogInformation(\"Email: {email}\", data.Email);\n }\n\n // In this example, we don't need to perform any asynchronous operations, so the\n // method doesn't need to be declared async.\n return Task.CompletedTask;\n }\n}\n```\n\n### Ruby\n\n require \"functions_framework\"\n\n # Triggered by creation or deletion of a Firebase Auth user object.\n FunctionsFramework.cloud_event \"hello_auth\" do |event|\n # Event-triggered Ruby functions receive a CloudEvents::Event::V1 object.\n # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html\n # The Firebase event payload can be obtained from the `data` field.\n payload = event.data\n\n logger.info \"Function triggered by creation/deletion of user: #{payload['uid']}\"\n logger.info \"Created at: #{payload['metadata']['createdAt']}\"\n logger.info \"Email: #{payload['email']}\" if payload.key? \"email\"\n end\n\n### PHP\n\n```php\nuse Google\\CloudFunctions\\CloudEvent;\n\nfunction firebaseAuth(CloudEvent $cloudevent)\n{\n $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');\n $data = $cloudevent-\u003egetData();\n\n fwrite(\n $log,\n 'Function triggered by change to user: ' . $data['uid'] . PHP_EOL\n );\n fwrite($log, 'Created at: ' . $data['metadata']['createTime'] . PHP_EOL);\n\n if (isset($data['email'])) {\n fwrite($log, 'Email: ' . $data['email'] . PHP_EOL);\n }\n}\n```\n\n### Deploying your function\n\nTo deploy your function, you need to specify the event type and the project for\nwhich you have Firebase Auth configured. In the Google Cloud console, there\nis a single field for **Event Type** as the project is assumed to be the same as\nthe project that contains your function.\n\nOn the command line, however, you must use specific strings to specify these two\nparameters. The following `gcloud` command deploys a function that is triggered\nby user `create` events: \n\n```bash\ngcloud functions deploy FUNCTION_NAME \\\n --no-gen2 \\\n --entry-point ENTRY_POINT \\\n --trigger-event providers/firebase.auth/eventTypes/user.create \\\n --trigger-resource YOUR_PROJECT_ID \\\n --runtime RUNTIME\n```\n| **Note:** When you deploy a function using the Google Cloud CLI, the command must include the name of the function contained in your code that you want the `deploy` command to execute. You can specify that function using either `FUNCTION_NAME` or the optional `--entry-point` flag, depending on the needs of your implementation. See the [deployment guide](/functions/1stgendocs/deploy#basics) for more discussion."]]