Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Implement a Next.js application with middleware for internationalized routing.

  1. User

    Implement a Next.js application with middleware for internationalized routing.

  2. Assistant

    Implementing middleware for i18n in Next.js

    The user is asking for a Next.js application with middleware for internationalized routing. They didn't specify the version, but I'll assume it's the modern Next.js 13 or 14 app router. I need to include code for middleware.ts, i18n configuration for locales like /en and /fr, and ensure dynamic routing and locale detection are part of the solution. It seems they want an explanation that’s concise but still code-heavy, specifically using middleware for i18n routing, even though Next.js has built-in options.Setting up Next.js with middleware for i18n

    I'm thinking about setting up a Next.js project using npx create-next-app@latest. For next.config.js, it seems that with middleware-based custom i18n, I might not need to define built-in i18n at all. Instead, I can treat the locale prefix as part of the pathname. With Next 13+, I can create a directory structure like /app/[locale]/....

    For middleware.ts, I’ll import tools and configure supported locales as an array, along with a utility function getLocale(request) to extract the user's locale from either a cookie or the Accept-Language header. I'll focus on parsing for the best match with minimal logic.Implementing Next.js middleware for i18n

    Since I'm ChatGPT, I can focus on creating a simple parsing method to handle locale selection using weights. The middleware needs to check if the pathname indicates static files, API routes, or Next assets. If it does, I’ll let it pass through.

    If it has a locale in the first segment, I’ll ensure the cookie is set; if not, I’ll redirect to the appropriate locale. I also want to set the NEXT_LOCALE cookie accordingly and configure the matcher to run middleware only for pages. Additionally, I'll include an example for app/[locale]/layout.tsx, verifying the locale for support and providing a notfound response. I’ll demonstrate the minimal setup to align with the user’s request for step-by-step implementation.Planning Next.js i18n implementation

    I’m assuming we’re working with the modern Next.js App Router. I should outline the project to implement localization with middleware.

    First, I’ll introduce the concept of redirecting users to localized paths and showing fallbacks. Next, I'll list prerequisites before detailing the steps: creating the Next app, defining locales in a config file, and implementing middleware.ts with arrays for locales and helper functions.

    Then, I’ll explain how to route based on the locale in the app directory, including necessary files like layout.tsx and page.tsx. I might also suggest a locale switcher for easier navigation. Finally, I’ll touch on handling static assets, API routes, and caching. I need to include code segments for clarity.Detailing Next.js i18n middleware setup

    I'm designing specifics for the i18n.config.ts, where I'll define available locales and a default locale while ensuring there's a type check for valid locales. In middleware.ts, I want to import necessary functions and set up locale handling based on the Accept-Language header and cookies.

    The middleware checks for static assets or API paths to proceed normally. If the path doesn't have a locale segment, it determines the locale and redirects accordingly. I’ll also include code for the layout and page files, as well as an updated next.config.js that omits built-in i18n.

    Finally, I'll introduce a LocaleSwitcher component for users to change locales easily. I aim for clarity while providing step-by-step instructions along with code snippets, avoiding unnecessary lengthy intros. Below is a complete, minimal example of a Next.js (App Router) application that uses middleware.ts for internationalized routing.

    It will:

    • Support multiple locales (e.g. en, fr, de).
    • Automatically redirect / → /en, /fr, etc. based on cookie or Accept-Language.
    • Keep the locale prefix in the URL: /en, /fr/about, etc.
    • Store the chosen locale in a cookie (NEXT_LOCALE).

    1. Project setup

    npx create-next-app@latest my-i18n-app
    cd my-i18n-app
    

    Use the App Router (default in Next 13+).

    In next.config.js, do not configure the built-in i18n (we’re rolling our own with middleware):

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      // Leave out the i18n: { ... } block when using custom middleware-based routing
    };
    
    module.exports = nextConfig;
    

    2. Shared i18n config

    Create i18n.config.ts in the project root:

    // i18n.config.ts
    export const locales = ['en', 'fr', 'de'] as const;
    export type Locale = (typeof locales)[number];
    
    export const defaultLocale: Locale = 'en';
    
    export function isLocale(locale: string | undefined): locale is Locale {
      return !!locale && (locales as readonly string[]).includes(locale);
    }
    

    3. Middleware for locale detection and routing

    Create middleware.ts in the project root:

    // middleware.ts
    import { NextRequest, NextResponse } from 'next/server';
    import { locales, defaultLocale, isLocale, Locale } from './i18n.config';
    
    const PUBLIC_FILE = /\.(.*)$/;
    
    function getLocaleFromAcceptLanguage(
      headerValue: string | null
    ): Locale {
      if (!headerValue) return defaultLocale;
    
      // Very simple parser: "en-US,en;q=0.9,fr;q=0.8"
      const languages = headerValue
        .split(',')
        .map((item) => item.split(';')[0]?.trim())
        .filter(Boolean) as string[];
    
      for (const lang of languages) {
        const base = lang.split('-')[0]; // "en-US" -> "en"
        if (isLocale(base)) return base;
      }
    
      return defaultLocale;
    }
    
    export function middleware(request: NextRequest) {
      const { pathname } = request.nextUrl;
    
      // Skip next internal files, API, and static assets
      if (
        pathname.startsWith('/_next') ||
        pathname.startsWith('/api') ||
        PUBLIC_FILE.test(pathname) ||
        pathname === '/favicon.ico'
      ) {
        return NextResponse.next();
      }
    
      const segments = pathname.split('/');
      const firstSegment = segments[1]; // e.g. "" | "en" | "fr" | "about"
    
      // If the first path segment is already a valid locale,
      // just ensure the cookie is set and continue.
      if (isLocale(firstSegment)) {
        const response = NextResponse.next();
        const localeInCookie = request.cookies.get('NEXT_LOCALE')?.value;
    
        if (localeInCookie !== firstSegment) {
          response.cookies.set('NEXT_LOCALE', firstSegment, {
            path: '/',
            maxAge: 365 * 24 * 60 * 60, // 1 year
          });
        }
    
        return response;
      }
    
      // No locale in the URL: pick one
      const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
      let locale: Locale = defaultLocale;
    
      if (isLocale(cookieLocale)) {
        locale = cookieLocale;
      } else {
        locale = getLocaleFromAcceptLanguage(
          request.headers.get('accept-language')
        );
      }
    
      // Redirect to the same path with the locale prefix
      const url = request.nextUrl.clone();
      url.pathname = `/${locale}${pathname}`;
    
      const response = NextResponse.redirect(url);
      response.cookies.set('NEXT_LOCALE', locale, {
        path: '/',
        maxAge: 365 * 24 * 60 * 60,
      });
    
      return response;
    }
    
    // Limit middleware to routes where we want i18n
    export const config = {
      matcher: [
        '/((?!_next|favicon.ico|robots.txt|sitemap.xml|static).*)',
      ],
    };
    

    Behavior examples:

    • / → redirects to /en (or /fr, /de based on header/cookie).
    • /about → redirects to /en/about, etc.
    • /en/about → served as-is, cookie set to en.

    4. App Router: locale-aware routes

    Create the folder app/[locale]/.

    4.1 app/[locale]/layout.tsx

    // app/[locale]/layout.tsx
    import type { ReactNode } from 'react';
    import { locales, type Locale, isLocale } from '../../i18n.config';
    import { notFound } from 'next/navigation';
    import './globals.css';
    
    export async function generateStaticParams() {
      return locales.map((locale) => ({ locale }));
    }
    
    export default function LocaleLayout({
      children,
      params,
    }: {
      children: ReactNode;
      params: { locale: string };
    }) {
      if (!isLocale(params.locale)) {
        notFound();
      }
    
      const locale = params.locale as Locale;
    
      return (
        <html lang={locale}>
          <body>
            <header style={{ padding: '1rem', borderBottom: '1px solid #ccc' }}>
              <strong>My i18n App</strong> – current locale: {locale}
            </header>
            <main style={{ padding: '1rem' }}>{children}</main>
          </body>
        </html>
      );
    }
    

    4.2 Home page for each locale

    app/[locale]/page.tsx:

    // app/[locale]/page.tsx
    import Link from 'next/link';
    import { type Locale, locales, isLocale } from '../../i18n.config';
    
    export default function HomePage({
      params,
    }: {
      params: { locale: string };
    }) {
      if (!isLocale(params.locale)) return null;
      const locale = params.locale as Locale;
    
      const greetingByLocale: Record<Locale, string> = {
        en: 'Hello',
        fr: 'Bonjour',
        de: 'Hallo',
      };
    
      return (
        <div>
          <h1>{greetingByLocale[locale]}!</h1>
          <p>This is the home page for locale: {locale}</p>
    
          <nav style={{ marginTop: '1rem' }}>
            <Link href={`/${locale}/about`}>About</Link>
          </nav>
    
          <LocaleSwitcher currentLocale={locale} />
        </div>
      );
    }
    
    // Simple client-side locale switcher
    'use client';
    
    import { useRouter, usePathname } from 'next/navigation';
    
    function LocaleSwitcher({ currentLocale }: { currentLocale: Locale }) {
      const router = useRouter();
      const pathname = usePathname(); // e.g. "/en" or "/en/about"
    
      const handleChange = (newLocale: Locale) => {
        const segments = pathname.split('/');
        segments[1] = newLocale; // replace old locale
        const newPath = segments.join('/') || '/';
        router.push(newPath);
      };
    
      return (
        <div style={{ marginTop: '1rem' }}>
          <label>
            Locale:&nbsp;
            <select
              value={currentLocale}
              onChange={(e) => handleChange(e.target.value as Locale)}
            >
              {locales.map((loc) => (
                <option key={loc} value={loc}>
                  {loc}
                </option>
              ))}
            </select>
          </label>
        </div>
      );
    }
    

    4.3 Another localized page

    app/[locale]/about/page.tsx:

    // app/[locale]/about/page.tsx
    import Link from 'next/link';
    import { type Locale, isLocale } from '../../../i18n.config';
    
    export default function AboutPage({
      params,
    }: {
      params: { locale: string };
    }) {
      if (!isLocale(params.locale)) return null;
      const locale = params.locale as Locale;
    
      const textByLocale: Record<Locale, string> = {
        en: 'This is the about page.',
        fr: "Ceci est la page à propos.",
        de: 'Dies ist die Über-Seite.',
      };
    
      return (
        <div>
          <h1>About ({locale})</h1>
          <p>{textByLocale[locale]}</p>
          <Link href={`/${locale}`}>Back to home</Link>
        </div>
      );
    }
    

    5. Run the app

    npm run dev
    # then open http://localhost:3000
    
    • Visiting / redirects to /<locale> based on cookie or browser language.
    • URLs always include a locale segment (/en, /fr/about, etc.).
    • Changing language via the <select> changes the route and the middleware will keep the cookie in sync.

    If you want, you can extend this with real translations (e.g., next-intl, i18next, etc.), but the routing/middleware part above is a complete working base.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.