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

Next.js跨域重定向在Firebase Hosting失效问题求助

解决Firebase Hosting下跨域名路由跳转失效问题

问题本质

框架自带的路由方法(比如你用的useRouter)本来就是用来处理同域名内的客户端路由跳转的,跨域名跳转根本不属于它的职责范围。Firebase Hosting的rewrites规则也只负责同域名路径的重写转发,不会管跨域跳转的事儿。本地开发能生效是因为本地没有Firebase的路由拦截逻辑,浏览器直接处理了外部链接跳转。

解决方案

直接替换跨域跳转的方式就行,别再用router.push处理外部域名:

// 直接跳转到目标域名
window.location.href = "https://www.example.com/auth";

// 如果需要新开标签页,用这个
window.open("https://www.example.com/auth", "_blank");

要是你非得保留用路由方法的写法(不推荐),可以在全局路由拦截里加判断,手动处理外部链接:

import { useRouter } from 'next/router';
import { useEffect } from 'react';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url) => {
      // 识别外部链接
      if (url.startsWith('http')) {
        window.location.href = url;
        return false; // 阻止默认路由行为
      }
    };

    router.events.on('routeChangeStart', handleRouteChange);
    return () => router.events.off('routeChangeStart', handleRouteChange);
  }, [router]);

  return <Component {...pageProps} />;
}

export default MyApp;

关于firebase.json的说明

你的rewrites配置没问题,它只负责同域名路径到HTML文件的映射,和跨域跳转无关,不需要修改这部分。后续如果要加更多同域名路由,继续添加rewrites规则就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:37:37