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

首次开发Next.js项目:多语言URL路由配置求助

基于next-intl实现多语言路由配置步骤

1. 确认依赖安装

确保已安装next-intl,执行以下命令:

npm install next-intl
# 或
yarn add next-intl

2. 配置i18n.ts文件

替换现有文件内容,定义支持的语言列表、默认语言,以及路由路径的多语言映射(补充剩余语言的对应路径即可):

// i18n.ts
import { createI18nClient } from 'next-intl';

// 支持的7种语言
export const locales = ['en', 'it', 'ru', 'tr', 'el', 'sr', 'ar'] as const;

// 路由路径的多语言映射,替换为各语言实际路径
export const pathnames = {
  '/products': {
    en: '/products',
    it: '/prodotti',
    tr: '/urunler',
    ru: '/tovary',
    el: '/proionta',
    sr: '/proizvodi'
  }
} as const;

export default createI18nClient({
  locales,
  defaultLocale: 'en',
  pathnames
});

3. 配置middleware.ts文件

更新现有文件,用next-intl中间件处理路由重定向与语言匹配:

// middleware.ts
import createMiddleware from 'next-intl/middleware';
import { locales, pathnames } from './i18n';

export default createMiddleware({
  locales,
  defaultLocale: 'en',
  pathnames
});

// 指定需要处理的路由规则,排除静态资源和API路由
export const config = {
  matcher: ['/', '/(en|it|ru|tr|el|sr|ar)/:path*']

};

4. 单一页面文件配置

无需为每种语言创建单独页面,只需在app目录下创建[locale]文件夹,编写统一页面文件:
比如创建app/[locale]/products/page.tsx,内容示例:

// app/[locale]/products/page.tsx
import { useLocale } from 'next-intl';

export default async function ProductsPage() {
  const locale = useLocale();
  
  // 根据当前语言调用对应API获取内容
  const products = await fetch(`/api/products?lang=${locale}`, { cache: 'no-store' })
    .then(res => res.json());
  
  return (
    <div dir={locale === 'ar' ? 'rtl' : 'ltr'}>
      {/* 渲染API返回的多语言内容 */}
      <h1>{products.title}</h1>
      {/* 其他页面内容 */}
    </div>
  );
}

关键说明

  • 所有页面统一放在[locale]目录下,next-intl会自动根据URL中的语言前缀和路径映射,将请求路由到对应页面文件
  • 访问www.domain.com/it/prodotti时,系统会匹配到[locale]/products/page.tsx,同时locale参数为it,直接调用对应API即可
  • 无需维护JSON翻译文件,完全通过API获取页面内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:11:11