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

NextJS集成next-i18next部署Firebase Functions后多语言路径404

解决Next.js + next-i18next部署Firebase Functions后多语言路由404问题

你的问题核心在于两个配置错误,加上路由跳转写法的小问题,以下是具体修复步骤:

1. 修正Firebase函数的Next.js应用初始化逻辑

当前server.js中每次请求都会执行app.prepare(),这会导致Next.js应用重复初始化,无法正确维护路由状态,尤其是多语言路由的解析。修改为只初始化一次:

const functions = require('firebase-functions');
const { default: next } = require('next');

const app = next({
  dev: false,
  conf: { distDir: '.next' },
});

const handle = app.getRequestHandler();
// 预先缓存应用准备的Promise,只执行一次
const prepareApp = app.prepare();

exports.nextSsrServer = functions
  .runWith({
    memory: '1GB',
  })
  .https.onRequest(async (req, res) => {
    await prepareApp;
    return handle(req, res);
  });

2. 关闭Firebase Hosting的cleanUrls设置

firebase.json中的cleanUrls: true会修改URL的解析规则,和Next.js的多语言路由系统冲突,导致带locale的路径无法正确匹配:

{
  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "function": "nextSsrServer"
      }
    ],
    "cleanUrls": false
  },
  "functions": {
    "source": ".",
    "runtime": "nodejs14"
  }
}

3. 修正路由跳转的写法

你当前的router.push('/', '/', { locale: 'en' })写法错误,第二个参数指定了as路径为/,导致无法跳转到/en。改用以下两种正确写法之一:

// 方法1:利用locale自动生成路径
router.push('/', { locale: 'en' });

// 方法2:直接指定目标路径
router.push('/en');

完成以上修改后,重新部署Firebase Functions和Hosting,多语言路由即可正常工作,包括模拟器环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:06:31