Next.js应用用next-i18next+getServerSideProps时出现指定错误崩溃
问题排查与解决方案
核心原因分析
报错no possibility found to get query是next-i18next尝试从请求上下文中解析locale参数时失败导致的,主要有两个关键问题:
- Next.js项目未配置内置的i18n路由规则,
next-i18next无法正确识别URL中的locale信息 getServerSideProps未调用next-i18next提供的serverSideTranslations方法,导致库无法获取必要的query上下文
步骤1:添加next-i18next配置文件
在项目根目录创建next-i18next.config.js,定义locale基础配置:
module.exports = { i18n: { defaultLocale: 'ru', // 设置默认语言 locales: ['uzc', 'kaa', 'ru'], // 匹配你的localeSubpaths配置 }, };
步骤2:修改next.config.js,集成i18n配置
更新你的next.config.js,引入并添加i18n配置:
const { nextI18NextRewrites } = require('next-i18next/rewrites') const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) const withImages = require('next-images') const { i18n } = require('./next-i18next.config'); // 引入i18n配置 const localeSubpaths = { uzc: 'uzc', kaa: 'kaa', ru: 'ru', } module.exports = withBundleAnalyzer( withImages({ env: { BASE_URL: process.env.NEXT_PUBLIC_BASE_URL || 'https://yyyyy/v1', }, publicRuntimeConfig: { localeSubpaths, }, i18n, // 新增i18n配置 rewrites: async () => nextI18NextRewrites(localeSubpaths), webpack(config) { config.module.rules.push({ test: /\.svg$/, use: ['@svgr/webpack'], }) return config }, }), )
步骤3:修复getServerSideProps逻辑
在页面文件中导入serverSideTranslations,并替换原有逻辑,确保next-i18next能正确获取query上下文:
import { serverSideTranslations } from 'next-i18next/serverSideTranslations' export const getServerSideProps = async (ctx) => { const { query } = ctx // 处理redirect逻辑,用可选链避免query为undefined时出错 if (query?.code) { return { redirect: { destination: '/', permanent: true, }, } } // 调用serverSideTranslations获取翻译配置,自动处理locale和query const translationProps = await serverSideTranslations( ctx.locale || 'ru', // 优先用上下文的locale, fallback到默认值 ['common', 'header', 'footer'] ) return { props: { ...translationProps, // 合并翻译props }, } }
额外注意事项
- 确保
next-i18next版本与你的Next.js版本兼容(比如Next.js 13+对应next-i18nextv13+) - 所有使用i18n的页面都需要通过
serverSideTranslations获取props,不要直接返回namespacesRequired
内容的提问来源于stack exchange,提问作者ABDULLOKH MUKHAMMADJONOV
相关产品推荐
相关产品推荐

