跳转至主要内容
Next.js i18n

支持 App Router 的 Next.js i18n

为 Next.js 应用提供 Server Components、ISR,以及边缘优化的翻译能力。

Package
lefine
Entry
lefine/next
Router
App Router
lefine
01终端
npm install lefine
02middleware.ts
// lefine.tsimport { createLefine } from 'lefine/next';export const lefine = createLefine({  project: 'app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b',  locales: ['en', 'de', 'fr', 'ja'],  defaultLocale: 'en',});// proxy.ts (middleware.ts before Next 16)import { lefine } from './lefine';export default lefine.proxy;export const config = { matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'] };
03components/HeroSection.tsx
'use client';import { useStrings } from 'lefine/react';export function HeroSection() {  const t = useStrings('home');  return <h1>{t('title')}</h1>;}
t('title')
Welcome
01/Setup

Set up in 4 steps

  1. 01

    安装

    将 @better-i18n/next 和 next-intl 添加到你的项目中。

    terminalbash
    npm install lefine
  2. 02

    添加用于语言环境检测的中间件(Next.js 16 中为 proxy.ts)

    中间件通过读取 URL 前缀、语言环境 cookie 和 Accept-Language 请求头来检测用户的语言环境,并据此进行重定向。

    middleware.ts
    // lefine.tsimport { createLefine } from 'lefine/next';export const lefine = createLefine({  project: 'app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b',  locales: ['en', 'de', 'fr', 'ja'],  defaultLocale: 'en',});// proxy.ts (middleware.ts before Next 16)import { lefine } from './lefine';export default lefine.proxy;export const config = { matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'] };
  3. 03

    在 Server Component 中加载消息

    在根 layout 中使用 getMessages() 在服务端获取翻译内容,并将其传递给 BetterI18nProvider。

    app/[locale]/layout.tsx
    // app/[locale]/layout.tsximport { lefine } from '@/lefine';export default async function RootLayout({ children, params }) {  const { locale } = await params;  return (    <html lang={locale}>      <body>        <lefine.Provider locale={locale} namespaces={['home']}>          {children}        </lefine.Provider>      </body>    </html>  );}
  4. 04

    在 Client Component 中使用翻译

    在任意 Client Component 中调用 useTranslations()。消息已经从服务端 hydrate 完成——无需额外请求。

    components/HeroSection.tsx
    'use client';import { useStrings } from 'lefine/react';export function HeroSection() {  const t = useStrings('home');  return <h1>{t('title')}</h1>;}
02/Routing

Proxy(Middleware)与区域设置检测

在页面渲染之前执行区域设置检测,并从边缘 CDN 加载消息,前端配有短时内存缓存。

01middlewaremiddleware.ts
02getRequestConfigi18n/request.ts
03getMessages()app/[locale]/page.tsx
04useTranslations()components/Hero.tsx
cdn.lefine.ai/{appId}/v/{version}/{locale}/translations.jsonmax-age=60

中间件设置

只需一个中间件文件,即可为你的 Next.js 应用添加语言环境检测和路由功能。

middleware.ts
// proxy.ts (middleware.ts before Next 16) — locale detectionimport { lefine } from './lefine'export default lefine.proxyexport const config = { matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'] }
middleware.ts
// middleware.ts — Edge-based locale detectionimport { NextRequest, NextResponse } from 'next/server';const SUPPORTED_LOCALES = ['en', 'de', 'fr', 'ja', 'es'] as const;const DEFAULT_LOCALE = 'en';function getPreferredLocale(request: NextRequest): string {  // 1. Check URL prefix  const pathname = request.nextUrl.pathname;  const urlLocale = SUPPORTED_LOCALES.find(    (l) => pathname.startsWith(`/${l}/`) || pathname === `/${l}`  );  if (urlLocale) return urlLocale;  // 2. Check cookie  const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;  if (cookieLocale && SUPPORTED_LOCALES.includes(cookieLocale as any)) {    return cookieLocale;  }  // 3. Parse Accept-Language header  const acceptLang = request.headers.get('accept-language') ?? '';  const preferred = acceptLang    .split(',')    .map((part) => part.split(';')[0].trim().substring(0, 2))    .find((code) => SUPPORTED_LOCALES.includes(code as any));  return preferred ?? DEFAULT_LOCALE;}export function middleware(request: NextRequest) {  const locale = getPreferredLocale(request);  const { pathname } = request.nextUrl;  const hasLocale = SUPPORTED_LOCALES.some(    (l) => pathname.startsWith(`/${l}/`) || pathname === `/${l}`  );  if (!hasLocale) {    return NextResponse.redirect(      new URL(`/${locale}${pathname}`, request.url)    );  }  return NextResponse.next();}export const config = {  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],};

兼容 Edge 的消息加载

使用轻量级的内存 TTL 缓存在边缘节点缓存翻译内容,实现即时响应。

lib/edge-strings.ts
// lib/edge-strings.ts — Edge-compatible string loadingimport { lefine } from '@/lefine';// Fetches are tagged and kept for 60 s (the edge's own max-age).// The publish webhook expires them at once.export async function getEdgeStrings(locale: string, namespace: string) {  return lefine.getStrings(locale, namespace);}

支持 i18n 的 Edge API 路由

从边缘路由处理程序返回已翻译的 API 响应。

app/api/translate/route.ts
// app/api/translate/route.ts — Edge API route with i18nimport { getEdgeStrings } from '@/lib/edge-strings';export const runtime = 'edge';export async function GET(request: Request) {  const url = new URL(request.url);  const locale = url.searchParams.get('locale') ?? 'en';  const key = url.searchParams.get('key') ?? '';  const t = await getEdgeStrings(locale, 'api-responses');  const translated = t(key);  return Response.json({ text: translated, locale });}
03/Rendering

情报、监视与侦察及国际化

结合增量静态再生成与i18n功能,实现快速、始终保持最新的多语言页面。

  1. Publish
  2. R2 write
  3. CDN purge
  4. Revalidate
  5. Page served
  • revalidate = 3600app/[locale]/layout.tsx~60 min
  • revalidate = 1800app/[locale]/[slug]/page.tsx~30 min
  • revalidatePath()app/api/revalidate/route.ts< 1 min

快速开始

只需几行代码即可将 i18n 添加到您的 Next.js 应用程序中。

app/[locale]/page.tsx
// app/[locale]/page.tsximport { lefine } from '@/lefine';export default async function Page({ params }: { params: Promise<{ locale: string }> }) {  const { locale } = await params;  const t = await lefine.getStrings(locale, 'home');  return (    <main>      <h1>{t('title')}</h1>      <p>{t('description')}</p>    </main>  );}
app/[locale]/layout.tsx
// app/[locale]/layout.tsx — ISR with i18nimport { lefine } from '@/lefine';export const revalidate = 3600; // Revalidate every hourexport default async function LocaleLayout({  children,  params,}: {  children: React.ReactNode;  params: Promise<{ locale: string }>;}) {  const { locale } = await params;  return (    <lefine.Provider locale={locale} namespaces={['common']}>      {children}    </lefine.Provider>  );}

使用 generateStaticParams 的 ISR

在构建时为每个语言环境预渲染页面,然后通过 ISR 按计划刷新。

app/[locale]/[slug]/page.tsx
// app/[locale]/[slug]/page.tsx — Generate static pages per localeimport { lefine } from '@/lefine';export async function generateStaticParams() {  const slugs = await fetchAllSlugs();  return lefine.locales.flatMap((locale) =>    slugs.map((slug) => ({ locale, slug }))  );}export const revalidate = 1800; // ISR: refresh every 30 minexport default async function Page({  params,}: {  params: Promise<{ locale: string; slug: string }>;}) {  const { locale, slug } = await params;  const t = await lefine.getStrings(locale, 'blog');  return <article><h1>{t(slug + '.title')}</h1></article>;}

按需重新验证

当翻译更新时触发 ISR 重新验证——接入 Lefine 的发布 webhook。

app/api/revalidate/route.ts
// app/api/i18n/revalidate/route.ts — On-demand ISR for translation updatesimport { lefine } from '@/lefine';// Called by the Lefine publish webhook. It checks the signature// (LEFINE_WEBHOOK_SECRET) and expires the cached strings at once.export const POST = lefine.revalidate;
04/Advanced

高级模式

嵌套布局、并行路由以及具有类型安全转换的服务器操作。

app/[locale]/dashboard/layout.tsx
// app/[locale]/dashboard/layout.tsx — Nested layout with namespaceimport { lefine } from '@/lefine';import { DashboardNav } from '@/components/DashboardNav';export default async function DashboardLayout({  children,  params,}: {  children: React.ReactNode;  params: Promise<{ locale: string }>;}) {  const { locale } = await params;  // Send the dashboard namespace alongside common strings  return (    <lefine.Provider locale={locale} namespaces={['common', 'dashboard']}>      <DashboardNav />      <main>{children}</main>    </lefine.Provider>  );}

支持 i18n 的并行路由

在并行路由插槽中独立加载翻译,实现模块化、支持多语言环境的布局。

app/[locale]/@analytics/page.tsx
// app/[locale]/@analytics/page.tsx — Parallel route with i18nimport { getTranslations } from 'next-intl/server';export default async function AnalyticsSlot({  params,}: {  params: Promise<{ locale: string }>;}) {  const { locale } = await params;  const t = await getTranslations({ locale, namespace: 'analytics' });  return (    <section aria-label={t('title')}>      <h2>{t('title')}</h2>      <p>{t('description')}</p>    </section>  );}// app/[locale]/layout.tsx — Consuming parallel routesexport default function Layout({  children,  analytics,  notifications,}: {  children: React.ReactNode;  analytics: React.ReactNode;  notifications: React.ReactNode;}) {  return (    <div>      <main>{children}</main>      <aside>{analytics}</aside>      <aside>{notifications}</aside>    </div>  );}

支持翻译的 Server Action

从 server action 返回已翻译的校验错误和成功消息。

app/[locale]/contact/actions.ts
// app/[locale]/contact/actions.ts — Server action with i18n'use server';import { getTranslations } from 'next-intl/server';import { headers } from 'next/headers';export async function submitContactForm(formData: FormData) {  const headersList = await headers();  // The locale comes from the URL — see the routing section above  const locale = headersList.get('x-locale') ?? 'en';  const t = await getTranslations({ locale, namespace: 'contact' });  const email = formData.get('email') as string;  const message = formData.get('message') as string;  if (!email || !message) {    return { error: t('validation.required') };  }  try {    await sendEmail({ email, message, locale });    return { success: t('form.success') };  } catch {    return { error: t('form.error') };  }}// app/[locale]/contact/page.tsx — Using the server action'use client';import { useTranslations } from 'next-intl';import { submitContactForm } from './actions';export default function ContactPage() {  const t = useTranslations('contact');  return (    <form action={submitContactForm}>      <label>{t('form.email')}</label>      <input name="email" type="email" required />      <label>{t('form.message')}</label>      <textarea name="message" required />      <button type="submit">{t('form.submit')}</button>    </form>  );}
05/Troubleshooting

常见国际化问题的故障排除

修复水合不匹配问题、缺失的区域设置回退方案以及日期/数字格式差异。

// Fix: Hydration mismatch with date/number formatting// Problem: Server renders "1,000" but client renders "1.000"// Solution: lefine.Provider already passes an explicit timeZone (UTC by default)// to the client, so server and client share the same formatting.// app/[locale]/layout.tsximport { getFormatter } from 'next-intl/server';export default async function Layout({ children, params }: {  children: React.ReactNode;  params: Promise<{ locale: string }>;}) {  const { locale } = await params;  // Pre-format on server with the explicit locale  const format = await getFormatter({ locale });  return (    <html lang={locale} suppressHydrationWarning>      <body>{children}</body>    </html>  );}// components/Price.tsx — Client component'use client';import { useFormatter } from 'next-intl';export function Price({ amount }: { amount: number }) {  const format = useFormatter();  // useFormatter automatically uses the locale/timeZone from lefine.Provider  // ensuring server and client render the same output  return <span>{format.number(amount, { style: 'currency', currency: 'USD' })}</span>;}

语言环境回退链

定义回退链,使区域变体(如 pt-BR)先回退到 pt,再回退到 en。

lib/i18n-config.ts
// lib/i18n-config.ts — Locale fallback chainconst FALLBACK_CHAIN: Record<string, string[]> = {  'pt-BR': ['pt', 'en'],  'zh-TW': ['zh-CN', 'en'],  'en-GB': ['en'],  'de-AT': ['de', 'en'],};export function resolveMessages(  locale: string,  allMessages: Record<string, Record<string, string>>): Record<string, string> {  const chain = FALLBACK_CHAIN[locale] ?? ['en'];  const primary = allMessages[locale] ?? {};  // Merge fallback messages (primary overrides fallbacks)  return chain.reduceRight(    (merged, fallbackLocale) => ({      ...merged,      ...(allMessages[fallbackLocale] ?? {}),    }),    primary  );}

一致的日期格式化

通过显式地将 timeZone 设置为 UTC,避免服务端与客户端日期不一致。

components/LocalizedDate.tsx
// components/LocalizedDate.tsx — Consistent date formatting'use client';import { useFormatter, useLocale } from 'next-intl';export function LocalizedDate({ date }: { date: Date | string }) {  const format = useFormatter();  const locale = useLocale();  const dateObj = typeof date === 'string' ? new Date(date) : date;  return (    <time dateTime={dateObj.toISOString()}>      {format.dateTime(dateObj, {        year: 'numeric',        month: 'long',        day: 'numeric',        // Explicitly set timeZone to avoid server/client mismatch        timeZone: 'UTC',      })}    </time>  );}
06/Capabilities

功能

  • 支持 App Router,从 Server Components 到 Client Components
  • 通过中间件(Next.js 16 中为 proxy.ts)自动检测语言区域
  • 支持 React Server Components
  • 使用 generateStaticParams 进行静态生成
  • 增量静态再生 (ISR)
  • 类型安全的翻译
  • 边缘 CDN 分发
  • 使用 hreflang 进行 SEO 优化
  • 基于语言环境的路由
07/Integrations

兼容热门 Next.js i18n 库

Lefine 不是替代你喜欢的 i18n 库 — 而是让它们更强大的翻译管理层。

  • next-intl

    最受欢迎的 Next.js i18n 库,支持 App Router、类型安全消息和 ICU 语法。

    Lefine 将翻译以 next-intl 读取的 JSON 消息格式交付。在仪表板中管理,并通过 CDN 发布——无需重新部署。

  • next-i18next

    基于 i18next 的成熟 Next.js i18n 库。从 v16 开始,它同时支持 App Router 和 Pages Router。

    导出为 i18next 兼容的命名空间 JSON。Lefine 处理翻译工作流,next-i18next 处理运行时。

  • Lingui

    轻量级、基于宏的 i18n 库,具有出色的 DX 和自动消息提取。

    使用 Lingui CLI 将消息提取为 JSON 目录,在 Lefine 中管理翻译,并通过 GitHub 集成(beta)同步回来。

开始使用

免费开始。

开始使用 Next.js i18n 构建

提供免费层级。无需信用卡。