Accept-Language HTTP header to detect the user's locale?Next.js automatically reads the Accept-Language header on the server side during the initial request. It compares the languages listed in the header with the supported locales configured in next.config.js. The first matching locale is selected for rendering the page.
['en', 'fr']. The user has a cookie NEXT_LOCALE=fr but their browser sends Accept-Language: en-US,en;q=0.9. Which locale will Next.js use for rendering the page?Next.js prioritizes the locale stored in the NEXT_LOCALE cookie over the Accept-Language header. This allows user preferences to persist across sessions.
Accept-Language header and redirects to the matching locale path in Next.js 14+?Option A correctly uses request.headers.get to access the header, safely handles optional chaining, extracts the primary language code, and constructs a new URL for redirection.
Option A incorrectly accesses headers as an object, which is invalid. Option A misses optional chaining and can cause errors if header is missing. Option A incorrectly splits by semicolon instead of comma.
import { NextResponse } from 'next/server';
export function middleware(request) {
const acceptLang = request.headers.get('accept-language');
const locale = acceptLang.split(',')[0];
if (!['en', 'fr'].includes(locale)) {
return NextResponse.redirect(new URL('/en', request.url));
}
return NextResponse.next();
}The acceptLang.split(',')[0] returns values like 'en-US' or 'fr-FR'. Since the code checks if this full string is in ['en', 'fr'], it fails and redirects to '/en' every time.
To fix this, the code should extract only the primary language code before the dash.
Next.js encourages using the built-in i18n routing configured in next.config.js. It automatically detects locale from the Accept-Language header and cookies. Middleware can be used to redirect users to the correct locale path seamlessly.
Manual parsing or client-side detection is less efficient and can cause flicker or inconsistent routing.