0PricingLogin
Next.js 15 Fullstack (App Router + Server Actions) · Lesson

Locale Detection and Subpath Routing with Middleware

Detect the user locale and rewrite requests to localized subpaths in middleware.

What Is Locale Detection?

Internationalization (i18n) in Next.js 15 starts with locale detection: figuring out which language and region the visitor prefers before serving any content.

Detection typically reads from three sources, in order of priority:

  • URL subpath/en/about, /tr/about (most explicit)
  • Cookie — a previously saved preference like NEXT_LOCALE=fr
  • Accept-Language header — sent automatically by the browser

Next.js 15 removed its built-in i18n config in the App Router era, so you implement this logic yourself inside middleware. This gives you full control over matching rules, fallbacks, and redirects.

Project Setup: Supported Locales

Before writing middleware, define your supported locales and default locale in a shared constants file. This single source of truth is imported by middleware, layout components, and any locale-aware utility.

A common convention is a lib/i18n.ts file that exports:

  • locales — the full list of supported locale strings
  • defaultLocale — the fallback when no match is found
  • A helper type for type-safe locale values
// lib/i18n.ts
export const locales = ['en', 'tr', 'de', 'fr'] as const;
export type Locale = (typeof locales)[number];
export const defaultLocale: Locale = 'en';

export function isValidLocale(value: string): value is Locale {
  return (locales as readonly string[]).includes(value);
}

All lessons in this course

  1. Locale Detection and Subpath Routing with Middleware
  2. Server-Side Translation Loading and Message Catalogs
  3. Localized Metadata, Sitemaps, and hreflang
  4. Formatting Dates, Numbers, and Plurals by Locale
← Back to Next.js 15 Fullstack (App Router + Server Actions)