You need to enable JavaScript to run this app. 是否可不使用Next.js国际化路由,用next-i18next实现仅Cookie控制多语言
优惠活动
大模型
产品
解决方案
定价
更多

是否可不使用Next.js国际化路由,用next-i18next实现仅Cookie控制多语言

完全可以用next-i18next实现你的需求,不需要退回使用react-i18next + i18next的基础组合,只需调整少量配置即可满足仅Cookie识别语言、无国际化路由的要求,具体操作如下:

1. 关闭Next.js内置国际化路由配置

在next.config.js中删除所有i18n相关的配置项,不要声明locale、defaultLocale等参数,避免Next.js自动生成带语言前缀的路由。

2. 调整next-i18next配置,仅保留Cookie语言检测

修改next-i18next.config.js文件,配置示例如下:

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'it', 'de'], // 填入你项目需要支持的所有语言编码
    localeDetection: false, // 关闭Next.js默认的自动语言检测逻辑
  },
  detection: {
    order: ['cookie'], // 仅保留Cookie作为语言识别来源
    lookupCookie: 'next-i18n-lang', // 指定读取语言的Cookie名称,和你需求里的命名一致
    caches: ['cookie'], // 语言切换后也存入该Cookie
  },
  serializeConfig: false,
}

3. 服务端渲染适配(仅SSR/SSG场景需要)

如果你项目用到了服务端渲染,在getServerSideProps中手动读取Cookie传入翻译方法即可:

import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

export async function getServerSideProps(context) {
  const currentLocale = context.req.cookies['next-i18n-lang'] || 'en'
  return {
    props: {
      ...(await serverSideTranslations(currentLocale, ['common'])),
    },
  }
}

纯客户端渲染场景无需额外处理,next-i18next会自动按照配置读取Cookie中的语言值加载对应翻译。

补充说明

  • 切换语言时直接修改next-i18n-lang的Cookie值,再调用i18n.changeLanguage方法即可,不需要跳转路由
  • 你提到的next.router的locale属性无法开箱使用的问题确实存在,直接从i18n.language获取当前语言值使用即可,不影响核心功能

以上配置完全可以覆盖你的需求:

  • 无Cookie或者Cookie值为en时,访问https://app.example.com默认显示英文版本
  • Cookienext-i18n-lang设置为IT、DE等其他支持的语言时,访问同域名自动显示对应翻译版本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:51:02