Next.js链接在Firebase Hosting跳转异常:点击/account跳转到/acc
问题
我用Firebase Hosting部署了Next.js项目,所有页面都带有包含“Account”按钮的Navbar组件,该按钮是指向/account的Next.js Link。本地测试时跳转正常,但部署到Firebase托管站点后点击该链接会跳转到/acc。奇怪的是,在Chrome中悬停该按钮或右键复制链接地址,显示的都是/account。
Navbar组件代码
export default function Navbar({ currentUser, handleSignOut, handleSignIn, }: NavbarProps) { return ( <div className="w-full h-20 flex justify-between items-center px-5 fixed top-0"> <div className="flex-shrink-0 h-full"> <Link href="/"> <div className="h-full w-48 relative"> <Image src="/white.png" alt="Logo" layout="fill" style={{ objectFit: "contain", objectPosition: "left" }} /> </div> </Link> </div> <div className="flex gap-4"> {currentUser ? ( <> <Link href="/account" as={"/account"} className="bg-white text-black py-2 px-5 rounded-lg hover:bg-gray-200 font-bold font-roboto-flex-bold" onClick={(e) => { console.log( "Account link clicked, href:", e.currentTarget.href ); }} > Account </Link> <button onClick={() => { handleSignOut(); }} className="bg-none text-white py-2 px-5 rounded-lg font-bold font-roboto-flex-bold" > Sign Out </button> </> ) : ( <> <button onClick={() => { handleSignIn(); }} className="bg-white text-black py-2 px-5 rounded-lg hover:bg-gray-200 font-bold font-roboto-flex-bold" > Sign Up </button> <button onClick={() => { handleSignIn(); }} className="bg-none text-white py-2 px-5 rounded-lg font-bold font-roboto-flex-bold" > Login </button> </> )} </div> </div> ); }
next.config.js代码
/** @type {import('next').NextConfig} */ const nextConfig = { output: "export", images: { unoptimized: true, }, trailingSlash: true, }; module.exports = nextConfig;
firebase.json代码
{ "firestore": { "rules": "firestore.rules", "indexes": "firestore.indexes.json" }, "functions": [ { "source": "functions", "codebase": "default", "ignore": [ "node_modules", ".git", "firebase-debug.log", "firebase-debug.*.log", "*.local" ] } ], "hosting": { "source": "frontend", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "frameworksBackend": { "region": "us-central1" } } }
解决方案
1. 移除as属性
你在Link组件中额外添加的as={"/account"}属性,在Next.js静态导出模式(output: "export")下完全不需要,反而可能干扰路由解析逻辑。直接删除该属性,仅保留href="/account"即可。
2. 配置Firebase Hosting重写规则
针对静态导出的Next.js项目,需要在firebase.json的hosting字段中添加重写规则,确保所有路由请求都指向index.html,保证客户端路由正常工作:
"hosting": { // 保留原有配置 "rewrites": [ { "source": "**", "destination": "/index.html" } ] }
3. 清理缓存重新部署
Firebase Hosting可能缓存了旧的路由配置,执行以下步骤彻底更新:
- 本地重新构建项目:
npm run build - 清理Firebase缓存:
firebase deploy --only hosting:clean - 重新部署站点:
firebase deploy --only hosting
4. 检查Next.js版本兼容性
确认你使用的Next.js版本与Firebase Hosting的frameworksBackend兼容,版本差异可能导致路由解析异常。如果使用的是较旧版本,建议升级到稳定版后重新部署。
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

