Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

next-i18n-router

i18nexus205.5kMIT5.5.1TypeScript support: included

Next.js App Router internationalized routing and locale detection.

next.js, nextjs, react-intl, i18n, locale, detection, internationalization, internationalisation, localization, localisation, app router

readme

next-i18n-router

Adds internationalized routing for Next.js apps that use the App Router

App Router internationalized routing 🎉

Why is this library needed?

With the release of the App Router, internationalized routing has been removed as a built-in Next.js feature. This library adds back internationalized routing in addition to locale detection and optional cookie usage to set a user's preferred language.

This library can be used with any of the popular Javascript i18n libraries such as react-i18next and react-intl. Tutorials and examples can be found here.

Installation

npm install next-i18n-router

Example Usage

First, nest all pages and layouts inside of a dynamic segment named [locale]:

└── app
    └── [locale]
        ├── layout.js
        └── page.js

Create a file called i18nConfig.js at the root of your project to store your config:

const i18nConfig = {
  locales: ['en', 'de', 'ja'],
  defaultLocale: 'en'
};

module.exports = i18nConfig;

Create a middleware.js file at the root of your project (or in /src if using /src directory) where the i18nRouter will be used to provide internationalized redirects and rewrites:

import { i18nRouter } from 'next-i18n-router';
import i18nConfig from './i18nConfig';

export function middleware(request) {
  return i18nRouter(request, i18nConfig);
}

// only applies this middleware to files in the app directory
export const config = {
  matcher: '/((?!api|static|.*\\..*|_next).*)'
};

You now have internationalized routing!

Config Options

Option Default value Type Required?
locales | string[]
defaultLocale | string
prefixDefault false boolean
localeDetector (See below) function | false
localeCookie 'NEXT_LOCALE' string
noPrefix false boolean
serverSetCookie 'always' "always" | "if-empty" | "never"
cookieOptions (See below) object
basePath '' string

Locale Path Prefixing

By default, the defaultLocale's path is not prefixed with the locale. For example, if defaultLocale is set to en and locales is set to ['en', 'de'], the paths will appear as follows:

English: /products

German: /de/products

To also include your default locale in the path, set the prefixDefault config option to true.

To hide all locales from the path, set the noPrefix config option to true.

Locale Detection

By default, this library parses the request's accept-language header and determines which of your locales is preferred using @formatjs/intl-localematcher. This logic can be disabled or customized using the localeDetector config option (below).

Using the accept-language header is the recommended strategy outlined in the Next.js docs and is similar to the previous Pages Router implementation.

Custom Locale Detection (optional)

If you would prefer to handle locale detection yourself, you can set the localeDetector option with your own locale detection function:

const i18nConfig = {
  locales: ['en', 'de', 'ja'],
  defaultLocale: 'en',
  localeDetector: (request, config) => {
    // your custom locale detection logic
    return 'the-locale';
  }
};

module.exports = i18nConfig;

You can also set the localeDetector option to false if you wish to opt out of any locale detection.

You can override the localeDetector using the NEXT_LOCALE=the-locale cookie. For example, you can set this cookie when a user opts to change to a different language. When they return to your site, their preferred language will already be set.

If you would prefer to use a different cookie key other than NEXT_LOCALE, you can set the localeCookie option.

serverSetCookie (optional)

The serverSetCookie option automatically changes a visitor's preferred locale cookie by simply visiting a pathname that contains a locale.

'always'(default): When the pathname of a request includes a locale, that locale will be set as the cookie by the middleware. This means that locale detection and any existing locale cookie will be ignored if a locale exists in the request's pathname. Locale detection and the reading of any existing cookie will still be run on pathnames that do not include a locale.

'if-empty': Same as 'always', except the middleware will not overwrite the cookie if one already exists.

'never': The middleware will not automatically set the cookie.

If you are using noPrefix, the serverSetCookie option does not do anything since there is no locale in the pathname to read from. All language changing must be done by setting the cookie manually.

cookieOptions (optional)

The server sets the cookie by setting the Set-Cookie HTTP response header on the NextResponse. (Learn More)

By default, cookieOptions is set to:

{
  sameSite: 'strict',
  maxAge: 31536000,
  path: {the basePath of the incoming NextRequest}
}

You can set your own cookieOptions object containing any of the valid Set-Cookie attributes: MDN: Set-Cookie

Using basePath (optional)

This is only needed if you are using the basePath option in next.config.js. You will need to also include it as the basePath option in your i18nConfig.

As can be read about here, you will also need to update your matcher in your middleware config to include { source: '/' }:

export const config = {
  matcher: ['/((?!api|static|.*\\..*|_next).*)', { source: '/' }]
};

Getting the current locale

In a Client Component:

The current locale can be retrieved in a Client Component using the useCurrentLocale hook:

'use client';

import { useCurrentLocale } from 'next-i18n-router/client';
import i18nConfig from '@/i18nConfig';

function ExampleClientComponent() {
  const locale = useCurrentLocale(i18nConfig);

  ...
}

In a Server Component:

The current locale should be accessed from the component's params props:

function ExampleServerComponent({ params: { locale } }) {
  ...
}

Usage with popular i18n libraries

react-i18next

The maintainers of i18next recommend using react-i18next with the App Router instead of next-i18next. The popular next-i18next library is built specifically for the Pages Router. This means that if you are currently migrating from the Pages Router and use next-i18next, you will need to refactor to use react-i18next.

For a full walkthrough on setting up react-i18next with next-i18n-router (plus Google Translate/DeepL integration), see this tutorial.

You can also find an example project here.

react-intl

The react-intl library works great with the App Router. But it does require a litte extra configuration for usage in Server Components.

For a full walkthrough on using react-intl with next-i18n-router (plus Google Translate/DeepL integration), see this tutorial.

You can also find an example project here.

FAQ

How do I create a dropdown for a user to change the language?

In our example projects you will find a LanguageChanger component showing how to do this. Note that router.refresh is called after changing languages. This is because Next will not route the request through the middleware if the page happens to be cached on the client. router.refresh ensures the middleware is run on language change, allowing the locale cookie to be set properly.

My not-found page is not working. What's wrong?

This is likely because of our use of the [locale] dynamic segment. This is not a bug with this library. It is a design choice of NextJS when using a not-found page in a dynamic segment. To solve this, we recommend making the adjustment described here.

changelog

5.5.1

  • Fixes bug that caused an unnecessary extra redirect due to trailing slash in pathname

5.5.0

  • Add cookieOptions config option for setting custom Set-Cookie attributes

5.4.3

  • Remove console warning in localeDetector when invalid accept-language header present

5.4.2

  • Fixes bug where noPrefix did not use localeDetector when no cookie present

5.4.1

  • Update next dev dependency to 14.2.2

5.4.0

  • Add config option noPrefix for hiding the locale prefix in the pathname.
  • useCurrentLocale now checks the document cookie for the current locale prior to checking the pathname.

5.3.0

  • Change default of serverSetCookie to "always".
  • Add "never" option to serverSetCookie. This is the same as undefined in previous versions.

5.2.1

  • Update dependencies

5.2.0

  • Change to cookie redirect behavior: When visiting a pathname that includes a locale, the middleware will now redirect if the localeCookie is set. Previously the redirecting based on cookie only occured on pathnames without a locale, but we've decided this is inconsistent behavior.
  • Add serverSetCookie config option

5.1.0

Add forwarding of request headers in i18nRouter

5.0.2

Fixes RangeError thrown by @formatjs/intl-localematcher when an invalid accept-language header is present on request

5.0.1

Update examples to v5 and update changelog

5.0.0

To encourage best practices, we have removed the 'rewrite' routing strategy and require use of a dynamic segment.

Breaking Changes

If you are currently using routingStrategy: 'dynamicSegment', no changes are required aside from removing the routingStrategy option from your config.

  • routingStrategy config option removed
  • Dynamic segment for the path locale now required
  • Removed currentLocale helper function. This function used a header set in the middleware to get the current locale, but this was undependable due to middleware response caching. Reading headers in server components also disables use of SSG. To get the current locale in server components, you can now just use the page params.

4.1.2

4.1.1

  • Minor updates to README adding instructions for setup with i18next.

4.1.0

  • Fix bug in which rewrites did not have an opening /, causing pathnames with more than 2 segments to return 404's

4.0.0

  • Adds new option named routingStrategy that can be set to "rewrite" (default) or "dynamicSegment".
    • The "rewrite" strategy is the same functionality as v3.
    • The "dynamicSegment" strategy allows for using the current locale as a dynamic segment, enabling usage of generateStaticParams for static generation of all languages at build time.

Breaking Changes

  • i18nRewriter has been removed as it is no longer needed. 🎉
  • i18nRouter no longer accepts an existing response as a third argument.

3.3.0

TypeScript optimization:

  • Return undefined instead of null in useCurrentLocale hook
  • Return undefined instead of null in currentLocale helper

3.2.0

  • Update: Adds optional third argument of type NextResponse to i18nRouter to allow for developers to use a previously generated response (#8)
  • Fix: The original request's search parameters are now persisted when redirecting to another language (#13)

3.1.0

  • Adds basePath config option to support using the Next config basePath
  • Adds the currentLocale helper function for retrieving the current language in Server Components
  • Adds the useCurrentLocale hook for retrieving the current language in Client Components

3.0.0

  • Pathname language prefix for the default language no longer required
  • Remove need for [lang] dynamic segment by introducing the i18nRewriter
  • getLocale option replaced with localeDetector
  • Cookie detection now independent of localeDetector detection
  • Add config option for prefixDefault

Breaking changes

  • i18nRouter is no longer a default import
// v2.0.0
import i18nRouter from 'next-i18n-router';

// v3.0.0
import { i18nRouter } from 'next-i18n-router';
  • i18nRewriter must be used to create language paths in next.config.js
  • getLocale has been replaced with localeDetector
  • To continue having the default language's pathname prefixed, the prefixDefault option should be set to true

2.0.0

  • Library rewritten in Typescript
  • Typings for the i18nRouter config now available

1.0.2

  • Fix bug causing the locale cookie to not be read

1.0.1

  • Add repository to package.json
  • Minor README fixes

1.0.0

  • Initial Release