You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase模拟器套件中运行beforeUserCreated阻塞函数?

问题描述

使用Firebase Functions Gen2 JavaScript Node版本,启用Firebase Auth(带Identity Platform),仅使用模拟器时,beforeUserCreated阻塞函数未被调用。其他函数正常运行,不符合条件的用户仍被创建,日志无错误。

代码如下:

import * as v2 from "firebase-functions/v2";

import {
    beforeUserCreated,
    beforeUserSignedIn,
  } from "firebase-functions/v2/identity";

export const helloworld = v2.https.onRequest((request, response) => {
    response.send("Hello from Firebase!");
});


export const beforeusercreated = beforeUserCreated({ region: 'europe-west1' }, (event) => {
    const user = event.data;
  // Only users of a specific domain can sign up.
    if (!user.email || !user.email.endsWith("@example.com")) {
        throw new HttpsError("invalid-argument", "Unauthorized email");
    }
  });

模拟器日志:

✔ functions[us-central1-beforeusercreated]: providers/cloud.auth/eventTypes/user.beforeCreate function initialized (http://127.0.0.1:5101/univus-9457e/us-central1/beforeusercreated).

尝试修改函数名称无效,寻求解决方案。


解决方案

1. 修复区域不匹配问题

从日志可见,函数实际在us-central1区域初始化,但代码中指定了europe-west1。区域不匹配会导致Auth事件无法正确触发对应的函数:

  • 方法一:修改代码中的区域为us-central1,与模拟器默认区域保持一致;
  • 方法二:在firebase.json中设置Functions的默认区域为europe-west1,确保模拟器读取代码配置:
    {
      "functions": {
        "source": "functions",
        "region": "europe-west1"
      }
    }
    

修改后重启模拟器,使用命令firebase emulators:start --only auth,functions。

2. 导入缺失的HttpsError类

代码中使用HttpsError但未导入,会导致函数运行时报错,需补充导入语句:

import * as v2 from "firebase-functions/v2";
import { HttpsError } from "firebase-functions/v2/https"; // 新增此行
import {
    beforeUserCreated,
    beforeUserSignedIn,
  } from "firebase-functions/v2/identity";

3. 确保Auth与Functions模拟器联动

  • 前端代码中需明确连接到Auth模拟器,避免调用生产环境Auth服务:
    import { getAuth } from "firebase/auth";
    const auth = getAuth();
    if (process.env.NODE_ENV === "development") {
      auth.useEmulator("http://localhost:9099");
    }
    
  • 启动模拟器时必须同时启动Auth和Functions服务,单独启动会导致联动失败,执行命令:
    firebase emulators:start --only auth,functions
    

4. 添加调试日志验证触发状态

在beforeUserCreated函数中添加日志输出,便于确认函数是否被触发:

export const beforeusercreated = beforeUserCreated({ region: 'europe-west1' }, (event) => {
    console.log("beforeUserCreated函数已触发,用户数据:", event.data);
    const user = event.data;
    if (!user.email || !user.email.endsWith("@example.com")) {
        throw new HttpsError("invalid-argument", "Unauthorized email");
    }
  });

内容的提问来源于stack exchange,提问作者Brandon Haynes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:22:28