0
0
NextJSframework~30 mins

Sub-path routing for locales in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Sub-path routing for locales in Next.js
📖 Scenario: You are building a website that supports two languages: English and Spanish. You want users to see the language in the URL as a sub-path, like /en for English and /es for Spanish.
🎯 Goal: Create a Next.js app that uses sub-path routing to show content in English or Spanish based on the URL prefix /en or /es.
📋 What You'll Learn
Create a Next.js page component that shows a greeting message.
Add a configuration variable to define supported locales.
Use Next.js routing to detect the locale from the URL sub-path.
Render the greeting message in the correct language based on the locale.
💡 Why This Matters
🌍 Real World
Many websites support multiple languages and show the language in the URL to help users and search engines understand the content language.
💼 Career
Knowing how to implement locale-based routing is important for building internationalized web apps that reach a global audience.
Progress0 / 4 steps
1
Create the greeting messages object
Create a constant called greetings that is an object with two keys: en and es. Set en to the string 'Hello!' and es to the string '¡Hola!'.
NextJS
Need a hint?

Use const greetings = { en: 'Hello!', es: '¡Hola!' }.

2
Define supported locales array
Create a constant called locales that is an array containing the strings 'en' and 'es'.
NextJS
Need a hint?

Use const locales = ['en', 'es'];.

3
Create the Next.js page component with locale detection
Create a default exported React functional component called HomePage. Use the Next.js useRouter hook to get the router object. Get the locale using router.locale, defaulting to 'en' if not present. Render a <main> element with a <h1> that shows the greeting message from greetings for the detected locale.
NextJS
Need a hint?

Use const locale = router.locale || 'en';

4
Add Next.js config for i18n sub-path routing
Create a next.config.js file exporting an object with an i18n property. Set locales to the locales array and defaultLocale to 'en'. This enables Next.js sub-path routing for locales.
NextJS
Need a hint?

Use module.exports = { i18n: { locales: ['en', 'es'], defaultLocale: 'en' } }.