📖 Scenario: You are building a simple Next.js app that shows a greeting message in different languages based on the user's locale.To do this, you will detect the user's locale using different strategies and display the correct greeting.
🎯 Goal: Create a Next.js app that detects the user's locale using a cookie, a URL parameter, and the Accept-Language header, then shows a greeting message in the detected language.
📋 What You'll Learn
Create a Next.js page with a basic HTML structure
Add a cookie named locale to store the user's preferred language
Detect the locale from the cookie, URL query parameter, or Accept-Language header in order
Display a greeting message in English, Spanish, or French based on the detected locale
💡 Why This Matters
🌍 Real World
Websites often need to show content in the user's language automatically. Detecting locale helps improve user experience by showing greetings and content in the right language.
💼 Career
Understanding locale detection is important for frontend developers working on internationalized websites and apps, especially using frameworks like Next.js.
Progress0 / 4 steps
1
Set up initial greetings data
Create a constant object called greetings with keys en, es, and fr. Each key should have a greeting string: 'Hello' for English, 'Hola' for Spanish, and 'Bonjour' for French.
NextJS
Hint
Use a JavaScript object with keys for each language code and greeting strings as values.
2
Add locale detection config
Create a constant array called localePriority with the values 'cookie', 'query', and 'header' to define the order of locale detection.
NextJS
Hint
Use an array to list the detection methods in order.
3
Implement locale detection logic
Write a function called detectLocale that takes req as a parameter. Inside, check for a locale cookie, then a locale query parameter, then the Accept-Language header. Return the first matching locale code 'en', 'es', or 'fr'. If none found, return 'en' as default.
NextJS
Hint
Check each source in order and return the first valid locale found.
4
Complete Next.js page with greeting display
Create a default export async function called Page that takes { req } as a parameter. Inside, call detectLocale(req) to get the locale. Return JSX with a <main> element containing an <h1> that shows the greeting from greetings for the detected locale. Use semantic HTML and ensure accessibility.
NextJS
Hint
Use the detected locale to set the lang attribute and show the greeting inside an <h1>.
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
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 D
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
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 A
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?
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
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 A
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
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.