Localization is an essential feature for modern web applications, ensuring that users see content in their preferred language. Next.js provides built-in support for internationalization (i18n), making it easier to manage multiple locales. One common requirement is retrieving the current locale in a Next.js application.
In this topic, we will explore different ways to get the current locale in Next.js, including using Next.js router, Next.js middleware, and third-party libraries like next-intl.
Understanding Locales in Next.js
A locale represents the language and region settings for a user. In Next.js, locales are typically managed using:
- Internationalized Routing (built-in support from Next.js)
- Custom Context or Middleware
- Third-party libraries like next-intl or react-intl
Before retrieving the current locale, it is important to configure your Next.js app properly for internationalization.
1. Configuring Next.js for Internationalization
To enable i18n routing in Next.js, modify your next.config.js
file:
module.exports = {i18n: {locales: ['en', 'es', 'fr'], // Define supported localesdefaultLocale: 'en', // Set default locale},};
With this configuration, Next.js will automatically handle locale-based routing. For example:
/en/page
(English version)/es/page
(Spanish version)/fr/page
(French version)
Now, let’s explore different ways to get the current locale in Next.js.
2. Getting the Current Locale Using Next.js Router
The simplest way to get the current locale is by using the Next.js router. The useRouter
hook provides access to the locale value.
Example: Get Locale with useRouter
import { useRouter } from 'next/router';const CurrentLocale = () => {const router = useRouter();const { locale } = router;return <p>Current Locale: {locale}</p>;};export default CurrentLocale;
How It Works:
useRouter()
retrieves the Next.js router object.router.locale
gives the current active locale.
This approach is useful for displaying the current locale in UI elements like language switchers.
3. Getting the Locale on the Server (getServerSideProps & getStaticProps)
If you need to fetch the locale on the server, you can use getServerSideProps
or getStaticProps
.
Example: Get Locale in getServerSideProps
export async function getServerSideProps({ locale }) {return {props: { currentLocale: locale },};}const Page = ({ currentLocale }) => {return <p>Current Locale: {currentLocale}</p>;};export default Page;
How It Works:
locale
is available in thecontext
parameter ofgetServerSideProps
.- The value is passed as a prop to the page.
This approach is useful when you need the locale before rendering dynamic content.
4. Using Next.js Middleware to Get Locale
If you need to determine the locale before a request reaches a page, you can use Next.js middleware.
Example: Middleware for Locale Detection
import { NextResponse } from 'next/server';export function middleware(req) {const locale = req.nextUrl.locale || 'en'; // Default to English if no locale is foundconsole.log('Current Locale:', locale);return NextResponse.next();}
How It Works:
- Middleware runs before rendering a page.
req.nextUrl.locale
fetches the locale from the request URL.
This method is useful for redirecting users based on their locale or applying locale-specific logic.
5. Using next-intl to Manage Locales
next-intl is a popular library for managing translations and locale settings in Next.js applications. It simplifies working with multiple languages.
Installation
Run the following command to install next-intl:
npm install next-intl
Example: Get Locale with next-intl
import { useLocale } from 'next-intl';const CurrentLocale = () => {const locale = useLocale();return <p>Current Locale: {locale}</p>;};export default CurrentLocale;
How It Works:
useLocale()
automatically retrieves the active locale.- Works seamlessly with translation files and context.
This is an excellent approach if you need i18n support with structured translations.
6. Creating a Custom Locale Context
If you need global locale state management, you can create a custom React context.
Example: Locale Context Provider
import { createContext, useContext, useState } from 'react';import { useRouter } from 'next/router';const LocaleContext = createContext();export const LocaleProvider = ({ children }) => {const { locale } = useRouter();const [currentLocale, setLocale] = useState(locale);return (<LocaleContext.Provider value={{ currentLocale, setLocale }}>{children}</LocaleContext.Provider>);};export const useLocale = () => useContext(LocaleContext);
How It Works:
- Uses React context to store the current locale globally.
- Allows for locale updates across multiple components.
This is a great option if you need custom locale handling beyond the built-in Next.js features.
7. Common Issues When Getting the Current Locale
1. Router Not Ready in useRouter
If you use useRouter
inside a component that loads dynamically, the router may not be available immediately. To fix this:
const router = useRouter();if (!router.isReady) return null; // Ensure router is ready
2. Middleware Not Applying the Correct Locale
If you use middleware but the locale is incorrect, check the next.config.js
file to ensure locales are properly configured.
3. Server-Side Rendering Issues with Locale
When using getServerSideProps
, make sure the locale is correctly passed down as a prop to prevent hydration mismatches.
Getting the current locale in Next.js is crucial for internationalization. The best approach depends on your specific use case:
- useRouter(): For retrieving the locale in client-side components.
- getServerSideProps(): When locale data is needed on the server.
- Middleware: For pre-processing locale before rendering.
- next-intl: For structured i18n management.
- Custom context: For global locale state across an app.
By implementing the right strategy, you can ensure your Next.js app delivers a seamless multilingual experience.