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

Next.js index.tsx SSR动态路由与国际化路径配置问题

问题分析与解决方案

核心问题根源

你当前出现en/en这类嵌套路径的原因,是错误地同时使用了index.tsx和[locale].tsx,并且在getStaticPaths中将locale作为动态路由参数传递,与Next.js内置的国际化路由系统冲突。Next.js的i18n路由会自动为每个locale生成对应路径,手动创建动态locale页面会导致路径叠加。

正确配置步骤

1. 清理冗余文件

删除[locale].tsx,仅保留index.tsx作为首页入口——Next.js会自动为每个locale生成对应的首页路由,无需手动创建动态页面。

2. 修改index.tsx代码

import { getArticles } from "../utils/db/serverDb";
import ArticlesHome from "@/components/home/ArticlesHome";
import styles from "../styles/Home.module.css"; // 补充styles导入(你之前的代码遗漏了这部分)

export default function Home(props: { articles: any }) {
  return (
    <>
      <main className={styles.main}>
        <div className={styles.articleWrapper}>
          <ArticlesHome articles={props.articles} />
        </div>
      </main>
    </>
  );
}

export async function getStaticProps({ locale }: { locale: string }) {
  // 提取国家代码
  const country = locale !== "en" ? locale.split("-")[1] : "gb";
  // 获取对应国家的文章数据
  const articles = await getArticles(country, 3);
  
  return {
    props: {
      articles,
    },
    revalidate: 3600,
  };
}

export async function getStaticPaths() {
  // 为每个locale生成路径,params为空(首页无额外参数)
  const paths = locales.map(locale => ({
    params: {},
    locale: locale,
  }));

  return {
    paths,
    fallback: false,
  };
}

3. 可选:控制默认locale路径前缀

如果不想让默认locale生成/en路径,仅保留根路径/,可在next.config.js的i18n配置中添加prefixDefaultLocale: false:

i18n: {
  locales: ["en", "en-us", "en-gb", "en-au", "en-ca", "en-ie", "es-es", "es-co", "es-ar", "es-pe", "es-ve",  "es-cl",  "es-ec",  "es-bo"],
  defaultLocale: "en",
  prefixDefaultLocale: false, // 关闭默认locale的路径前缀
},

最终效果

构建后会生成符合预期的路径:

  • 默认locale en:/(若开启prefixDefaultLocale则同时生成/en)
  • 其他locale:/en-gb、/es-es、/es-co等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:37:02