为Next.js应用添加多语言翻译时遭遇next-i18next无法找到用户配置错误的求助
I’ve run into this exact error before, and it almost always comes down to a configuration naming convention issue or a missing explicit config reference in serverSideTranslations. Let’s walk through the fixes step by step:
1. Rename your config file to match next-i18next’s default convention
next-i18next automatically looks for a file named next-i18next.config.js by default. Your current config is named i18n.config.js, which the library can’t detect on its own.
Simply rename i18n.config.js to next-i18next.config.js, then update the import in your next.config.js:
// next.config.js require("dotenv").config(); const { i18n } = require("./next-i18next.config"); // Updated import path module.exports = { env: { API_BASE_URL: process.env.API_BASE_URL, SiteKey: process.env.SiteKey, SecretKey: process.env.SecretKey }, i18n };
2. Keep your original config filename (alternative fix)
If you want to stick with i18n.config.js, you need to explicitly pass your config to serverSideTranslations in every page where you use it. Here’s how to adjust your index.js:
import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import { useTranslation } from "next-i18next"; import i18nConfig from "./i18n.config"; // Import your custom config const Home = ({ expe }) => { const { t } = useTranslation("common"); // ... rest of your component code } export const getStaticProps = async ({ locale }) => { const res = await getExperiencias(2); const exp = await res.json(); return { props: { // Pass your config as the third argument to serverSideTranslations ...(await serverSideTranslations(locale, ["common", "footer", "navbar"], i18nConfig)), expe: exp } }; }; export default Home;
3. Double-check version compatibility
Make sure your next.js and next-i18next versions are compatible. For example, if you’re using Next.js 13+, you should be on the latest major version of next-i18next (v13+). Mismatched versions can cause unexpected config detection issues.
4. Verify your translation file structure
Ensure your translation files are stored in the default location: public/locales/{locale}/{namespace}.json. For example:
public/locales/en/common.jsonpublic/locales/fr/common.jsonpublic/locales/pt/common.json
If your translations are in a custom directory, add a localePath property to your config:
// next-i18next.config.js (or i18n.config.js) const path = require("path"); module.exports = { i18n: { locales: ["en", "fr", "pt"], defaultLocale: "pt" }, localePath: path.resolve("./your/custom/locale/directory") };
After making one of these changes, restart your development server and the error should be resolved.
内容的提问来源于stack exchange,提问作者Coyas

