Bird
Raised Fist0
NextJSframework~20 mins

Locale detection strategies in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Locale Detection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does Next.js detect locale using the Accept-Language header?
In Next.js, when using internationalized routing, how does the framework use the Accept-Language HTTP header to detect the user's locale?
ANext.js ignores the <code>Accept-Language</code> header and always defaults to the first locale in the configuration.
BNext.js requires manual parsing of the <code>Accept-Language</code> header in a custom middleware to detect locale.
CNext.js uses the <code>Accept-Language</code> header only on the client side after hydration to update the locale dynamically.
DNext.js reads the <code>Accept-Language</code> header on the server and matches the first supported locale from the header's list to set the locale.
Attempts:
2 left
💡 Hint
Think about how Next.js handles locale detection on the server before rendering.
❓ state_output
intermediate
2:00remaining
What locale is set when cookie and Accept-Language conflict?
Consider a Next.js app configured with locales ['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?
ANext.js will default to the first locale in the config, <code>en</code>, ignoring both cookie and header.
BThe locale from the cookie, <code>fr</code>, is used because cookies have higher priority.
CThe locale from the <code>Accept-Language</code> header, <code>en</code>, is used because it reflects the browser preference.
DNext.js will throw an error due to conflicting locale sources.
Attempts:
2 left
💡 Hint
Think about how Next.js prioritizes locale sources.
📝 Syntax
advanced
2:30remaining
Identify the correct middleware code for locale detection
Which middleware code snippet correctly detects the locale from the Accept-Language header and redirects to the matching locale path in Next.js 14+?
A
import { NextResponse } from 'next/server';
export function middleware(request) {
  const acceptLang = request.headers.get('accept-language');
  const locale = acceptLang?.split(',')[0].split('-')[0] || 'en';
  return NextResponse.redirect(new URL(`/${locale}`, request.url));
}
B
import { NextResponse } from 'next/server';
export function middleware(request) {
  const locale = request.headers['accept-language'].split(',')[0];
  return NextResponse.redirect(`/${locale}`);
}
C
import { NextResponse } from 'next/server';
export function middleware(request) {
  const locale = request.headers.get('accept-language').split(',')[0];
  return NextResponse.redirect(new URL(`/${locale}`, request.url));
}
D
import { NextResponse } from 'next/server';
export function middleware(request) {
  const acceptLang = request.headers.get('accept-language');
  const locale = acceptLang.split(';')[0];
  return NextResponse.redirect(new URL(`/${locale}`, request.url));
}
Attempts:
2 left
💡 Hint
Remember to safely access headers and parse the language code correctly.
🔧 Debug
advanced
2:30remaining
Why does locale detection fail in this Next.js middleware?
Given this middleware code snippet, why does locale detection fail and always redirect to '/en' regardless of the browser language?
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();
}
AThe code does not handle the case when <code>acceptLang</code> is null, causing a runtime error and fallback to '/en'.
BThe middleware does not return a response for valid locales, causing Next.js to default to '/en'.
CThe locale extracted includes region codes like 'en-US', which do not match 'en' or 'fr' exactly, causing the redirect.
DThe <code>includes</code> check is case-sensitive but the locale is always uppercase, causing mismatch.
Attempts:
2 left
💡 Hint
Look closely at how the locale string is extracted and compared.
🧠 Conceptual
expert
3:00remaining
What is the best practice for locale detection in Next.js 14+ with App Router?
In Next.js 14+, what is the recommended best practice for detecting and setting the user's locale for internationalized routing?
AUse the built-in Next.js i18n routing with <code>next.config.js</code> locales and rely on automatic detection via <code>Accept-Language</code> header and cookies, combined with middleware for redirects.
BManually parse the <code>Accept-Language</code> header in every server component and set locale state accordingly without using Next.js i18n config.
CUse client-side JavaScript to detect browser language and then reload the page with the correct locale path.
DDisable Next.js i18n routing and handle all locale detection and routing logic in custom Express.js middleware.
Attempts:
2 left
💡 Hint
Think about how Next.js integrates locale detection with routing and middleware.

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