Locale detection helps your website show content in the right language automatically. It makes visitors feel welcome by speaking their language without asking them.
Locale detection strategies in NextJS
export const middleware = (request) => { const locale = request.nextUrl.locale || 'en'; // Your locale detection logic here return NextResponse.next(); };
This example shows a basic middleware function in Next.js to detect locale.
You can access the locale from the request URL or headers.
import { NextResponse } from 'next/server'; export function middleware(request) { const acceptLanguage = request.headers.get('accept-language'); const locale = acceptLanguage?.split(',')[0].split('-')[0] || 'en'; const url = request.nextUrl.clone(); url.locale = locale; return NextResponse.rewrite(url); }
import { NextResponse } from 'next/server'; export function middleware(request) { const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value; const locale = cookieLocale || 'en'; const url = request.nextUrl.clone(); url.locale = locale; return NextResponse.rewrite(url); }
import { NextResponse } from 'next/server'; export function middleware(request) { const url = request.nextUrl.clone(); if (!url.locale || url.locale === 'default') { url.locale = 'en'; return NextResponse.redirect(url); } return NextResponse.next(); }
This middleware tries to detect the user's locale by first checking a cookie, then the browser's language header, and finally defaults to English. It redirects the user to the URL with the correct locale if needed.
import { NextResponse } from 'next/server'; export function middleware(request) { // Try to get locale from cookie const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value; // If no cookie, get from Accept-Language header const acceptLanguage = request.headers.get('accept-language'); const headerLocale = acceptLanguage?.split(',')[0].split('-')[0]; // Decide locale: cookie > header > default const locale = cookieLocale || headerLocale || 'en'; // Clone URL and set locale const url = request.nextUrl.clone(); url.locale = locale; // Redirect to URL with locale if different if (request.nextUrl.locale !== locale) { return NextResponse.redirect(url); } return NextResponse.next(); }
Always provide a default locale to avoid errors.
Use cookies to remember user language choices for better experience.
Check browser headers carefully as they can contain multiple languages.
Locale detection helps show the right language automatically.
You can detect locale from cookies, headers, or URL.
Next.js middleware is a good place to handle locale detection and redirects.
Practice
Solution
Step 1: Understand locale detection purpose
Locale detection is used to identify the user's language preference automatically.Step 2: Match purpose to options
Showing the website in the user's preferred language matches the purpose of locale detection.Final Answer:
To automatically show the website in the user's preferred language -> Option DQuick Check:
Locale detection = show preferred language [OK]
- Confusing locale detection with performance optimization
- Thinking it changes layout instead of language
- Mixing locale detection with analytics tracking
Solution
Step 1: Identify where locale config is set
Next.js uses the i18n field inside next.config.js to define supported locales.Step 2: Check other options
API files, _document.js, and CSS files do not configure locales.Final Answer:
next.config.js i18n field -> Option AQuick Check:
Locale config = next.config.js i18n [OK]
- Trying to configure locales in API routes
- Using _document.js for locale settings
- Assuming CSS files control language
export function middleware(request) {
const locale = request.headers.get('accept-language')?.split(',')[0].split('-')[0];
if (locale === 'fr') {
return Response.redirect(new URL('/fr', request.url));
}
return Response.next();
}Solution
Step 1: Analyze locale extraction from headers
The code extracts the first language code from the 'accept-language' header, e.g., 'fr'.Step 2: Check redirect condition
If locale is 'fr', the middleware redirects to '/fr' URL.Final Answer:
User is redirected to the /fr page -> Option BQuick Check:
Locale 'fr' triggers redirect to /fr [OK]
- Ignoring the redirect and assuming no change
- Confusing header parsing logic
- Assuming redirect to homepage always
export function middleware(request) {
const locale = request.headers.get('accept-language').split(',')[0];
if (locale === 'en') {
return Response.redirect(new URL('/en', request.url));
}
return Response.next();
}Solution
Step 1: Check headers.get usage
headers.get('accept-language') can return null if header missing, so calling split() without check causes error.Step 2: Identify fix
Using optional chaining like headers.get('accept-language')?.split(',')[0] prevents runtime error.Final Answer:
Missing optional chaining on headers.get could cause runtime error -> Option AQuick Check:
Null header needs optional chaining [OK]
- Assuming headers.get always returns string
- Incorrect redirect URL format
- Using invalid Response methods
Solution
Step 1: Understand priority order
We want to check cookie first, then header, then default 'en'.Step 2: Analyze each option
const locale = request.cookies.get('NEXT_LOCALE') || request.headers.get('accept-language')?.split(',')[0].split('-')[0] || 'en'; checks cookie first, then header with safe optional chaining, then 'en'. Others have wrong order or logic.Final Answer:
const locale = request.cookies.get('NEXT_LOCALE') || request.headers.get('accept-language')?.split(',')[0].split('-')[0] || 'en'; -> Option CQuick Check:
Cookie first, then header, then default [OK]
- Checking header before cookie
- Using && instead of || causing wrong logic
- Missing optional chaining on header
Ready to prove it?
Pass the test and this pattern moves unknown
