Zum Inhalt springen
Next.js i18n

Next.js‑i18n mit App Router

Server Components, ISR und edge‑optimierte Übersetzungen für Next.js‑Anwendungen.

Package
lefine
Entry
lefine/next
Router
App Router
lefine
01Terminal
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

    Installation

    Füge @better-i18n/next und next-intl zu deinem Projekt hinzu.

    terminalbash
    npm install lefine
  2. 02

    Middleware (proxy.ts in Next.js 16) zur Locale-Erkennung hinzufügen

    Die Middleware liest das URL-Präfix, das Locale-Cookie und den Accept-Language-Header, um die Locale des Nutzers zu erkennen und entsprechend weiterzuleiten.

    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

    Nachrichten in einer Server Component laden

    Verwende getMessages() in deinem Root-Layout, um Übersetzungen serverseitig zu laden und an BetterI18nProvider zu übergeben.

    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

    Übersetzungen in Client Components verwenden

    Rufe useTranslations() in jeder beliebigen Client Component auf. Die Nachrichten sind bereits vom Server hydratisiert – kein zusätzlicher Fetch nötig.

    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) und Erkennung der Ländereinstellung

Führen Sie die Erkennung der Ländereinstellungen vor dem Rendern der Seite durch und laden Sie Nachrichten aus dem Edge-CDN, mit einem kurzen In-Memory-Cache davor.

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

Middleware-Einrichtung

Füge deiner Next.js-App mit einer einzigen Middleware-Datei Locale-Erkennung und Routing hinzu.

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-kompatibles Laden von Nachrichten

Cache Übersetzungen am Edge mit einem leichtgewichtigen In-Memory-TTL-Cache für sofortige Antworten.

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);}

Edge-API-Route mit i18n

Gib übersetzte API-Antworten aus Edge-Route-Handlern zurück.

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

ISR und Internationalisierung

Kombinieren Sie inkrementelle statische Regenerierung mit i18n für schnelle, stets aktuelle mehrsprachige Seiten.

  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

Schnellstart

Fügen Sie i18n zu Ihrer Next.js‑App mit nur wenigen Zeilen Code hinzu.

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>  );}

ISR mit generateStaticParams

Rendere Seiten für jede Locale zur Build-Zeit vor und aktualisiere sie anschließend planmäßig mit 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>;}

On-Demand-Revalidierung

Löse eine ISR-Revalidierung aus, wenn Übersetzungen aktualisiert werden – über den Publish-Webhook von Lefine.

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

Fortgeschrittene Muster

Verschachtelte Layouts, parallele Routen und Serveraktionen mit typsicheren Übersetzungen.

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>  );}

Parallele Routen mit i18n

Lade Übersetzungen unabhängig in parallelen Routen-Slots für modulare, locale-bewusste Layouts.

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 Actions mit Übersetzung

Gib übersetzte Validierungsfehler und Erfolgsmeldungen aus Server Actions zurück.

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

Fehlerbehebung bei häufigen i18n-Problemen

Beheben Sie Probleme mit der Hydration, fehlende Locale-Fallbacks und Unterschiede bei der Datums-/Zahlenformatierung.

// 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>;}

Locale-Fallback-Kette

Definiere Fallback-Ketten, damit regionale Varianten wie pt-BR auf pt und dann auf en zurückfallen.

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  );}

Konsistente Datumsformatierung

Vermeide Datumsabweichungen zwischen Server und Client, indem du timeZone explizit auf UTC setzt.

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

Features

  • Support für App Router, von Server- bis Client-Komponenten
  • Middleware (proxy.ts in Next.js 16) zur automatischen Locale‑Erkennung
  • Support für React Server Components
  • Statische Generierung mit generateStaticParams
  • Incremental Static Regeneration
  • Typsichere Übersetzungen
  • Edge‑CDN‑Auslieferung
  • SEO‑optimiert mit hreflang
  • Locale‑basiertes Routing
07/Integrations

Funktioniert mit beliebten Next.js i18n-Bibliotheken

Lefine ersetzt nicht Ihre bevorzugte i18n-Bibliothek — es ist die Übersetzungsmanagement-Schicht, die sie noch leistungsfähiger macht.

  • next-intl

    Die beliebteste Next.js i18n-Bibliothek mit App Router-Unterstützung, typsicheren Nachrichten und ICU-Syntax.

    Lefine liefert Übersetzungen als die JSON-Messages, die next-intl liest. Verwalten Sie sie im Dashboard und veröffentlichen Sie über das CDN — ohne erneutes Deployment.

  • next-i18next

    Bewährte i18n-Bibliothek für Next.js basierend auf i18next. Seit v16 unterstützt sie neben dem Pages Router auch den App Router.

    Export im i18next-kompatiblen Namespace-JSON. Lefine übernimmt den Übersetzungsworkflow, next-i18next die Laufzeit.

  • Lingui

    Leichtgewichtige, makro-basierte i18n-Bibliothek mit exzellenter DX und automatischer Nachrichtenextraktion.

    Extrahieren Sie Nachrichten mit der Lingui CLI in JSON-Kataloge, verwalten Sie Übersetzungen in Lefine und synchronisieren Sie sie über die GitHub-Integration (beta) zurück.

Loslegen

Kostenlos starten.

Mit Next.js‑i18n loslegen

Kostenloser Tarif verfügbar. Keine Kreditkarte erforderlich.