I'm starting by identifying the core goal: a Next.js 13+ app, leveraging the App Router, with i18n managed by Middleware. This foundational understanding is crucial, a clear starting point for diving into the specifics of implementation.
Detailing the Architecture
My focus is now on mapping out the architectural components. The App Router's dynamic routing, middleware interception, and translation loading strategies are taking shape. I'm visualizing the flow from request to localized content, solidifying the interplay between these elements.
Mapping the Execution
Now I'm breaking down the project into discrete, actionable steps. First, initialize the Next.js setup. Configuration comes next, with locale definition and a directory structure blueprinting the app/[lang] dynamic routes. I envision a middleware.ts acting as the traffic director, handling locale detection and redirects, and also a translation loader to fetch localized JSON dictionaries. I'm focusing on the component layout now.
Finalizing Code and Structure
I'm now focusing on the code itself, detailing middleware configurations, exclusion patterns, and dynamic import strategies for dictionaries. Refining the get-dictionary.ts util function, along with the dynamic route structure within the app/[lang] directory, is key. I'll need to remember to clarify the use of generateStaticParams for proper static site generation.
Integrating the Details
I'm now deep-diving into the specifics, creating JSON dictionaries and the get-dictionary.ts util. Building the middleware logic, focusing on exclusion patterns for static assets and API routes, is key. I'm also thinking about the essential usage of generateStaticParams for SSG compatibility. I'm ensuring everything aligns with the Next.js 13+ App Router.
Mapping Out Implementation Steps
I'm now methodically planning the implementation. First, Next.js app initialization and locale configuration using a config file. Dictionary creation and a flexible utility for fetching those dictionaries follow. I'll need to define the middleware logic, and create the structure for dynamic routes and how they will handle translated content.
This guide demonstrates how to implement Internationalized (i18n) Routing in Next.js (App Router) using Middleware.
We will create a system where:
Content lives under specific language paths (e.g., /en/about, /fr/about).
Middleware detects the user's browser language preferences.
Users visiting the root / are redirected to their preferred language (e.g., /en).
Prerequisites
Install the necessary packages for locale matching:
Create a helper function to load the correct JSON file based on the locale. We use dynamic imports to keep the bundle size small (loading only what is needed).
File:lib/get-dictionary.ts
typescript
import 'server-only';
import type { Locale } from '../i18n-config';
const dictionaries = {
en: () => import('../dictionaries/en.json').then((module) => module.default),
fr: () => import('../dictionaries/fr.json').then((module) => module.default),
es: () => import('../dictionaries/en.json').then((module) => module.default), // Fallback or specific file
};
export const getDictionary = async (locale: Locale) => {
// If the locale isn't found in the map, fallback to 'en'
return dictionaries[locale]?.() ?? dictionaries.en();
};
Step 4: The Middleware
This is the core logic. It intercepts requests, checks if a locale is present in the URL, and if not, redirects based on the user's headers.
File:middleware.ts
typescript
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { i18n } from './i18n-config';
import { match as matchLocale } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
function getLocale(request: NextRequest): string | undefined {
// Negotiator expects plain object so we need to transform headers
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
// @ts-ignore locales are readonly
const locales: string[] = i18n.locales;
// Use negotiator and intl-localematcher to get best locale
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
);
const locale = matchLocale(languages, locales, i18n.defaultLocale);
return locale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// Check if there is any supported locale in the pathname
const pathnameIsMissingLocale = i18n.locales.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.redirect(
new URL(
`/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`,
request.url
)
);
}
}
export const config = {
// Matcher ignoring `/_next/` and `/api/`
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
Step 5: Create the Layout and Page Structure
Move your main application logic inside a dynamic route folder: app/[lang].
1. The Root Layout
Notice we put the lang attribute on the HTML tag.