Bird
Raised Fist0
NextJSframework~10 mins

Locale detection strategies in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Locale detection strategies
User visits site
↓
Check URL for locale
↓
Use URL
↓
Set locale
↓
Render page with locale
The site first looks at the URL for a locale. If none found, it checks the browser's language settings. Then it sets the locale and renders the page accordingly.
Execution Sample
NextJS
export function detectLocale(req) {
  const urlLocale = req.url.match(/^\/([a-z]{2})\//)?.[1];
  if (urlLocale) return urlLocale;
  return req.headers['accept-language']?.split(',')[0].slice(0, 2) || 'en';
}
This function tries to find the locale from the URL first, then from the browser's Accept-Language header, defaulting to 'en'.
Execution Table
StepInput URLAccept-Language HeaderURL Locale Found?Locale SelectedAction
1/fr/homeen-US,en;q=0.9frfrUse locale from URL
2/homees-ES,es;q=0.8noneesUse locale from Accept-Language header
3/homenonenoneenDefault to 'en' locale
4/de/aboutfr-FR,fr;q=0.7dedeUse locale from URL
5/aboutzh-CN,zh;q=0.6nonezhUse locale from Accept-Language header
💡 Locale is selected based on URL if present; otherwise, browser language header; defaults to 'en' if none found.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5
urlLocaleundefinedfrundefinedundefineddeundefined
acceptLanguageen-US,en;q=0.9en-US,en;q=0.9es-ES,es;q=0.8nonefr-FR,fr;q=0.7zh-CN,zh;q=0.6
localeundefinedfresendezh
Key Moments - 3 Insights
Why does the function check the URL before the Accept-Language header?
Because the URL locale is explicit and user-controlled, it takes priority over browser settings, as shown in execution_table rows 1 and 4.
What happens if neither URL nor Accept-Language header provides a locale?
The function defaults to 'en' as a safe fallback, demonstrated in execution_table row 3.
How does the function extract the locale from the URL?
It uses a regular expression to match the first two letters after the initial slash, as seen in the code and reflected in urlLocale values in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what locale is selected at step 2?
Afr
Ben
Ces
Dde
💡 Hint
Check the 'Locale Selected' column at step 2 in the execution_table.
At which step does the locale default to 'en'?
AStep 3
BStep 1
CStep 4
DStep 5
💡 Hint
Look for the row where both URL Locale Found? and Accept-Language Header are 'none' or missing.
If the URL was '/es/home' and Accept-Language was 'fr-FR', what locale would be selected?
Afr
Bes
Cen
Dnone
💡 Hint
URL locale has priority over Accept-Language header as shown in the concept_flow and execution_table.
Concept Snapshot
Locale detection in Next.js:
1. Check URL path for locale code (e.g., '/fr/') first.
2. If none, check browser Accept-Language header.
3. Default to 'en' if no locale found.
This ensures user preference or browser setting guides language.
Use regex to extract locale from URL.
Always have a fallback locale.
Full Transcript
When a user visits a Next.js site, the app tries to detect their language preference. First, it looks at the URL path to see if a locale code like 'fr' or 'de' is present. If it finds one, it uses that locale. If not, it checks the browser's Accept-Language header to guess the preferred language. If that is missing or empty, it defaults to English ('en'). This approach respects explicit user choices in the URL and falls back gracefully. The detection function uses a simple regular expression to extract the locale from the URL and splits the Accept-Language header to get the first language code. This logic helps the app render pages in the right language automatically.

Practice

(1/5)
1. What is the main purpose of locale detection in a Next.js application?
easy
A. To change the website layout based on screen size
B. To improve server response time by caching pages
C. To track user clicks for analytics
D. To automatically show the website in the user's preferred language

Solution

  1. Step 1: Understand locale detection purpose

    Locale detection is used to identify the user's language preference automatically.
  2. Step 2: Match purpose to options

    Showing the website in the user's preferred language matches the purpose of locale detection.
  3. Final Answer:

    To automatically show the website in the user's preferred language -> Option D
  4. Quick Check:

    Locale detection = show preferred language [OK]
Hint: Locale detection means showing language automatically [OK]
Common Mistakes:
  • Confusing locale detection with performance optimization
  • Thinking it changes layout instead of language
  • Mixing locale detection with analytics tracking
2. Which Next.js feature is commonly used to configure supported locales for automatic detection?
easy
A. next.config.js i18n field
B. pages/api/locale.js file
C. Custom _document.js file
D. Static CSS files

Solution

  1. Step 1: Identify where locale config is set

    Next.js uses the i18n field inside next.config.js to define supported locales.
  2. Step 2: Check other options

    API files, _document.js, and CSS files do not configure locales.
  3. Final Answer:

    next.config.js i18n field -> Option A
  4. Quick Check:

    Locale config = next.config.js i18n [OK]
Hint: Locales go in next.config.js under i18n [OK]
Common Mistakes:
  • Trying to configure locales in API routes
  • Using _document.js for locale settings
  • Assuming CSS files control language
3. Given this middleware snippet in Next.js, what happens when a user with 'fr' browser language visits the site?
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();
}
medium
A. User is redirected to the homepage
B. User is redirected to the /fr page
C. User gets a 404 error
D. User stays on the current page without redirect

Solution

  1. Step 1: Analyze locale extraction from headers

    The code extracts the first language code from the 'accept-language' header, e.g., 'fr'.
  2. Step 2: Check redirect condition

    If locale is 'fr', the middleware redirects to '/fr' URL.
  3. Final Answer:

    User is redirected to the /fr page -> Option B
  4. Quick Check:

    Locale 'fr' triggers redirect to /fr [OK]
Hint: Check header locale then redirect if matches [OK]
Common Mistakes:
  • Ignoring the redirect and assuming no change
  • Confusing header parsing logic
  • Assuming redirect to homepage always
4. Identify the error in this Next.js middleware code for locale detection:
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();
}
medium
A. Missing optional chaining on headers.get could cause runtime error
B. Redirect URL is incorrect, should be '/en-US'
C. Response.next() is not a valid method
D. Locale comparison should use locale.includes('en')

Solution

  1. Step 1: Check headers.get usage

    headers.get('accept-language') can return null if header missing, so calling split() without check causes error.
  2. Step 2: Identify fix

    Using optional chaining like headers.get('accept-language')?.split(',')[0] prevents runtime error.
  3. Final Answer:

    Missing optional chaining on headers.get could cause runtime error -> Option A
  4. Quick Check:

    Null header needs optional chaining [OK]
Hint: Always check headers.get may return null [OK]
Common Mistakes:
  • Assuming headers.get always returns string
  • Incorrect redirect URL format
  • Using invalid Response methods
5. You want to detect user locale in Next.js by checking cookie first, then header, and fallback to default 'en'. Which code snippet correctly implements this logic in middleware?
hard
A. const locale = 'en' || request.cookies.get('NEXT_LOCALE') || request.headers.get('accept-language');
B. const locale = request.headers.get('accept-language')?.split(',')[0].split('-')[0] || request.cookies.get('NEXT_LOCALE') || 'en';
C. const locale = request.cookies.get('NEXT_LOCALE') || request.headers.get('accept-language')?.split(',')[0].split('-')[0] || 'en';
D. const locale = request.cookies.get('NEXT_LOCALE') && request.headers.get('accept-language') || 'en';

Solution

  1. Step 1: Understand priority order

    We want to check cookie first, then header, then default 'en'.
  2. 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.
  3. Final Answer:

    const locale = request.cookies.get('NEXT_LOCALE') || request.headers.get('accept-language')?.split(',')[0].split('-')[0] || 'en'; -> Option C
  4. Quick Check:

    Cookie first, then header, then default [OK]
Hint: Use || in order: cookie, header, default [OK]
Common Mistakes:
  • Checking header before cookie
  • Using && instead of || causing wrong logic
  • Missing optional chaining on header
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard