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

Next.js调用setAppLanguage切换语言时getServerSideProps获取query为空

问题根因

next-translate 提供的 setAppLanguage 方法默认执行语言切换路由跳转时,不会自动携带当前URL的查询参数与哈希值,会导致跳转后路由上下文的query对象为空。你肉眼看到地址栏URL带查询参数,实际是客户端跳转时的临时显示,并未将参数正确传递给Next.js的路由系统,因此服务端执行getServerSideProps时无法读取到对应参数。

修复方案
  • 方案1:调用setAppLanguage时手动传入当前查询参数
    切换语言前读取当前页面的搜索参数,传入方法的第二个配置项即可:
    import setAppLanguage from 'next-translate/setLanguage'
    
    const switchLanguage = async (targetLang) => {
      // 保留当前页面所有查询参数
      const currentSearch = window.location.search
      await setAppLanguage(targetLang, { search: currentSearch })
    }
    
  • 方案2:全局配置自动保留查询参数(推荐)
    在项目根目录的next-translate配置文件(通常为i18n.js或i18n.json)中新增如下配置,所有语言切换操作都会自动携带当前的查询参数与哈希值,不需要每次手动传参:
    module.exports = {
      // 保留原有配置,如locales、defaultLocale、pages映射规则等
      setLanguageOptions: {
        preserveSearchParams: true,
        preserveHash: true
      }
    }
    
  • 额外排查点
    • 确认你使用的next-translate版本不低于1.2.0,低于该版本不支持全局保留查询参数的配置,需要先升级依赖包。
    • 检查pages/search/index.js的getServerSideProps逻辑,是否存在误过滤query参数的代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:24:04