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

Firebase Functions模拟器调用时context.auth始终为undefined

问题

使用Firebase模拟器搭建本地测试环境时,可调用云函数内context.auth取值始终为undefined。

涉及的云函数代码如下:

const functions = require('firebase-functions');
const util = require('util');

exports.helloWorld = functions.https.onCall(async (data, context) => {
  console.log("helloWorld", util.inspect(context.auth));
  return {
    auth: context.auth
  };
});

前端调用代码如下:

<script type="module">
    import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js';
    import {getAuth,connectAuthEmulator, signInAnonymously } from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-auth.js';
    import { getFunctions, connectFunctionsEmulator, httpsCallable } from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-functions.js';
    initializeApp({
      projectId: 'demo-project1',
      apiKey: 'dummy',
    });
    document.addEventListener('DOMContentLoaded', async function () {
      const auth = getAuth();
      connectAuthEmulator(auth, "http://localhost:9099");
      const functions = getFunctions();
      connectFunctionsEmulator(functions, "localhost", 6001);
      auth.onAuthStateChanged(user => {
        console.log("USER CHANGED TO ", user);
        if (user) {
          callFunction();
        }
      });
      await signInAnonymously(auth);
    });

    async function callFunction() {
      const functions = getFunctions();
      const helloWorld = httpsCallable(functions, 'helloWorld');
      let result = await helloWorld({ text: "hello" });
      console.log(result.data);
    };
  </script>
解决方案

按以下步骤排查修复即可:

  • 升级全局firebase-tools到最新版本,低版本存在demo测试项目鉴权上下文不传递的已知bug:
    npm install -g firebase-tools@latest
    
  • 启动模拟器时必须显式指定和前端初始化完全一致的项目ID,和代码里的demo-project1对应:
    firebase emulators:start --project=demo-project1
    
    启动时如果省略--project参数,模拟器会加载本地默认的firebase项目配置,和前端指定项目不匹配时会自动丢弃请求携带的鉴权信息,直接导致context.auth为undefined。
  • 修复后清空浏览器站点缓存(LocalStorage、SessionStorage)再刷新页面,避免旧的错误鉴权缓存影响结果。

注:现有代码里用onAuthStateChanged监听登录态再触发函数调用的逻辑是正确的,不需要额外调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:30:44