0
0
NextJSframework~30 mins

Locale detection strategies in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Locale Detection Strategies in Next.js
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use the detected locale to set the lang attribute and show the greeting inside an <h1>.