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

运行firebase serve --only functions时出现Cannot read property 'key' of undefined错误

Firebase Cloud Functions启动失败:TypeError: Cannot read property 'key' of undefined

错误信息

执行firebase serve --only functions时触发以下错误:

i  functions: Watching "/home/giuseppe/Documenti/projects/addlance/genial-lotto/functions" for Cloud Functions...
✔  functions: Using node@14 from host.
i  functions: Loaded environment variables from .env, .env.genial-lotto.
⬢  functions: Failed to load function definition from source: FirebaseError: Failed to load function definition from source: Failed to generate manifest from function source: TypeError: Cannot read property 'key' of undefined

问题原因

  1. 本地配置缺失:本地开发时未同步Firebase云端配置,functions.config()返回空对象,访问functions.config().private.key时因private未定义触发报错。
  2. 可选链使用不完整:configs/firebase.ts中部分functions.config()属性访问未使用可选链,配置不存在时直接访问子属性会抛出错误。
  3. 代码拼写错误:addCustomClaim函数中错误使用data.claim而非data.claims,调用时会触发属性访问错误。
  4. 重复初始化Admin:index.ts和configs/firebase.ts两处初始化Admin实例,可能导致初始化冲突。

解决方案

1. 同步云端配置到本地

在functions目录下执行以下命令,将云端配置同步到本地的.runtimeconfig.json文件:

firebase functions:config:get > .runtimeconfig.json

2. 完善配置访问的可选链

修改functions/src/configs/firebase.ts,确保所有functions.config()的属性访问都使用可选链:

import * as admin from "firebase-admin";
import * as functions from "firebase-functions";

admin.initializeApp({
  credential: admin.credential.cert({
    privateKey: functions.config().private?.key?.replace(/\\n/g, "\n"),
    projectId: functions.config().project?.id,
    clientEmail: functions.config().client?.email,
  }),
  databaseURL: "****",
});

const db = admin.firestore();
const realtime = admin.database();
export {admin, db, realtime};

3. 修复拼写错误

修改index.ts中addCustomClaim函数的拼写错误:

exports.addCustomClaim = functions.https.onCall((data) => {
  return admin.auth().getUserByEmail(data.email).then((user) => {
    return admin.auth().setCustomUserClaims(user.uid, data.claims).
        then(() => {
          return {
            message: ` Success!claims ${Object.keys(data.claims)} have been set on ${data.email}`,
          };
        }).catch((err) => {
          return {error: err};
        });
  });
});

4. 移除重复的Admin初始化

删除index.ts中的Admin初始化代码,保留configs/firebase.ts中的初始化即可:

// 移除以下代码块
// if (admin.apps.length === 0) {
// admin.initializeApp();
// }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:20:00