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

Microsoft Edge默认跟踪阻止模式导致Next.js中Firebase连接失败

解决Edge浏览器跟踪阻止模式下Firebase Auth无法访问的问题

问题根源

Edge浏览器的平衡跟踪阻止模式会自动拦截被判定为"跟踪器"的第三方跨域请求,而Firebase Auth依赖的身份验证端点(如identitytoolkit.googleapis.com、Google OAuth相关服务)属于跨域第三方资源,会被该模式误判拦截,导致登录流程失败。关闭跟踪阻止后,这些请求恢复正常,所以出现了仅Edge下异常的情况。

解决方案

1. 用户侧临时调整(快速生效)

引导用户针对当前站点关闭跟踪阻止:

  • 点击Edge地址栏左侧的「跟踪阻止」图标
  • 选择「允许此网站的跟踪」选项
  • 刷新页面后重新测试登录流程

2. 代码层面配置同域代理(无需用户操作)

通过Next.js的API路由代理Firebase Auth请求,将跨域请求转为同域请求,避免被跟踪阻止拦截:

  1. 在项目根目录安装代理依赖:
npm install http-proxy-middleware
  1. 创建代理路由文件 pages/api/firebase-auth-proxy.js:
import { createProxyMiddleware } from 'http-proxy-middleware';

export default createProxyMiddleware({
  target: 'https://identitytoolkit.googleapis.com',
  changeOrigin: true,
  pathRewrite: { '^/api/firebase-auth-proxy': '' },
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
});
  1. 修改Firebase Auth初始化代码,将请求指向代理地址:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = { /* 你的Firebase配置 */ };
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

// 开发环境使用本地代理,生产环境替换为你的域名
if (process.env.NODE_ENV === 'development') {
  auth.useEmulator('http://localhost:3000/api/firebase-auth-proxy');
} else {
  auth._apiKey = process.env.NEXT_PUBLIC_FIREBASE_API_KEY;
  auth._authDomain = `${process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID}.firebaseapp.com`;
  auth._customAuthDomain = `${window.location.origin}/api/firebase-auth-proxy`;
}

3. 添加HTTP安全头声明(告知Edge允许资源)

通过Next.js配置Permissions-Policy和Content-Security-Policy头,明确告知Edge这些Firebase资源不属于跟踪器:
修改next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: [
          {
            key: 'Permissions-Policy',
            value: 'interest-cohort=(), tracking-protection=()',
          },
          {
            key: 'Content-Security-Policy',
            value: "script-src 'self' 'unsafe-eval' 'unsafe-inline' https://www.gstatic.com https://*.firebaseio.com https://identitytoolkit.googleapis.com; connect-src 'self' https://www.gstatic.com https://*.firebaseio.com https://identitytoolkit.googleapis.com",
          },
        ],
      },
    ];
  },
};

module.exports = nextConfig;

验证步骤

  1. 开启Edge浏览器的「平衡跟踪阻止」模式
  2. 启动Next.js项目,测试登录流程
  3. 打开Edge开发者工具(F12)→ 「网络」面板,确认Firebase Auth相关请求状态为200,无拦截记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:33:11