首页 > 解决方案 > 尝试使用提供的 localeSubpaths 配置访问任何页面时出现 next-i18next 404 错误

问题描述

尝试访问 Next.js 应用程序的任何页面时,我都遇到了 404 问题。

当没有localeSubpaths提供配置时,应用程序可以正常工作。

实施localeSubpaths配置(next.config.js)后:

const localeSubpaths = {
  en: "en",
  "de-DE": "de-DE",
  fr: "fr"
};

应用程序不再工作。

每次我尝试访问主根目录/或任何语言环境页面fr时,de-DE浏览器都会显示 404 错误页面(自定义 Next.js 错误页面)。此页面包含一些可以正常工作的翻译内容。

页面还包含指向/主页的链接。当我通过单击链接导航到主页时 - >主页正确加载(包括相关翻译)

i18n.tsx配置文件:

import NextI18Next from "next-i18next";
import getConfig from "next/config";
import path from "path";

const { publicRuntimeConfig } = getConfig();
const { localeSubpaths } = publicRuntimeConfig;

const NextI18NextInstance = new NextI18Next({
  defaultLanguage: "en",
  ns: ["common"],
  defaultNS: "common",
  otherLanguages: ["de-DE", "de-CH", "fr"],
  strictMode: false,
  localeSubpaths,
  localePath: path.resolve("./public/static/locales")
});

export default NextI18NextInstance;

const {
  appWithTranslation,
  i18n,
  Link,
  withTranslation,
  Router
} = NextI18NextInstance;

export { appWithTranslation, i18n, Link, withTranslation, Router };

标签: javascriptinternationalizationnext.jsreact-i18nextnext-i18next

解决方案


确保您没有在 next.config.js 文件中定义任何 i18n 条目,因为这将与重定向条目重叠。

next.config.js

const localeSubpaths = {
  en: 'en',
  es: 'es'
}
[...]
//remove any reference to this entry
//i18n: [...]
rewrites: async () => nextI18NextRewrites(localeSubpaths),
  publicRuntimeConfig: {
    localeSubpaths,
  } 

i18n.ts

import NextI18Next from 'next-i18next'
import path from 'path'
 
const localeSubpaths = {
  en: 'en',
  es: 'es'
}

const NextI18NextInstance = new NextI18Next({
  browserLanguageDetection: false,
  ns: ["common"],
  defaultNS: "common",
  fallbackLng: 'en',
  otherLanguages: ['es'],
  localeSubpaths: localeSubpaths,
  defaultLanguage: 'en',
  localePath: path.resolve('./public/locales'),
})

export const { appWithTranslation, useTranslation, withTranslation, Link, i18n} = NextI18NextInstance;
export default NextI18NextInstance;


推荐阅读