Next.js › Internationalization (i18n) in Next.js

How can middleware help automatically detect a visitor's preferred language and redirect them accordingly?

Intermediate

Answer

Middleware can inspect the accept-language header sent by the browser, compare it against the languages your application supports, and redirect the visitor to the matching locale prefixed URL if they land on a page without one specified, giving each visitor a personalized starting experience.
// middleware.js
import { NextResponse } from 'next/server';

export function middleware(request) {
  const preferredLocale = getPreferredLocale(request.headers.get('accept-language'));
  if (!request.nextUrl.pathname.startsWith(`/${preferredLocale}`)) {
    return NextResponse.redirect(new URL(`/${preferredLocale}${request.nextUrl.pathname}`, request.url));
  }
}
Real-world example A visitor from Germany opening a company's website without specifying a language is automatically redirected to the German version, thanks to middleware reading their browser's language preference.

Common follow-ups: What happens if a visitor's browser language is not one of the supported locales?;Should this redirect happen every visit or only the first time?