Skip to content
Docs
Routing

Next.js internationalized routing

๐Ÿ’ก

Routing APIs are only needed when you're using i18n routing.

next-intl integrates with the routing system of Next.js in two places:

  1. Middleware: Negotiates the locale and handles redirects & rewrites
  2. Navigation APIs: Provides APIs to navigate between pages

This enables you to express your app in terms of APIs like <Link href="/about">, while aspects like the locale and user-facing pathnames are automatically handled behind the scenes (e.g. /de/ueber-uns).

Shared configuration

While the middleware provides a few more options than the navigation APIs, the majority of the configuration is shared between the two and should be used in coordination. Typically, this can be achieved by moving the shared configuration into a separate file like src/config.ts:

src
โ”œโ”€โ”€ config.ts
โ”œโ”€โ”€ middleware.ts
โ””โ”€โ”€ navigation.ts

This shared module can be set up like this:

config.ts
// A list of all locales that are supported
export const locales = ['en', 'de'] as const;
 
// ...

โ€ฆ and imported into both middleware.ts and navigation.ts:

middleware.ts
import createMiddleware from 'next-intl/middleware';
import {locales, /* ... */} from './config';
 
export default createMiddleware({
  locales,
  // ...
 
  // Used when no locale matches
  defaultLocale: 'en'
});
 
export const config = {
  // Match only internationalized pathnames
  matcher: ['/', '/(de|en)/:path*']
};
src/navigation.ts
import {createSharedPathnamesNavigation} from 'next-intl/navigation';
import {locales, /* ... */} from './config';
 
export const {Link, redirect, usePathname, useRouter} =
  createSharedPathnamesNavigation({locales, /* ... */});

Locale prefix

By default, the pathnames of your app will be available under a prefix that matches your directory structure (e.g. app/[locale]/about/page.tsx โ†’ /en/about). You can however adapt the routing to optionally remove the prefix or customize it per locale by configuring the localePrefix setting.

Always use a locale prefix (default)

By default, pathnames always start with the locale (e.g. /en/about).

config.ts
import {LocalePrefix} from 'next-intl/routing';
 
export const localePrefix = 'always' satisfies LocalePrefix;
 
// ...
How can I redirect unprefixed pathnames?

If you want to redirect unprefixed pathnames like /about to a prefixed alternative like /en/about, you can adjust your middleware matcher to match unprefixed pathnames too.

Don't use a locale prefix for the default locale

If you only want to include a locale prefix for non-default locales, you can configure your routing accordingly:

config.ts
import {LocalePrefix} from 'next-intl/routing';
 
export const localePrefix = 'as-needed' satisfies LocalePrefix;
 
// ...

In this case, requests where the locale prefix matches the default locale will be redirected (e.g. /en/about to /about). This will affect both prefix-based as well as domain-based routing.

Note that:

  1. If you use this strategy, you should make sure that your middleware matcher detects unprefixed pathnames.
  2. If you use the Link component, the initial render will point to the prefixed version but will be patched immediately on the client once the component detects that the default locale has rendered. The prefixed version is still valid, but SEO tools might report a hint that the link points to a redirect.

Never use a locale prefix

If you'd like to provide a locale to next-intl, e.g. based on user settings, you can consider setting up next-intl without i18n routing. This way, you don't need to use the routing integration in the first place.

However, you can also configure the middleware to never show a locale prefix in the URL, which can be helpful in the following cases:

  1. You're using domain-based routing and you support only a single locale per domain
  2. You're using a cookie to determine the locale but would like to enable static rendering
config.ts
import {LocalePrefix} from 'next-intl/routing';
 
export const localePrefix = 'never' satisfies LocalePrefix;
 
// ...

In this case, requests for all locales will be rewritten to have the locale only prefixed internally. You still need to place all your pages inside a [locale] folder for the routes to be able to receive the locale param.

Note that:

  1. If you use this strategy, you should make sure that your matcher detects unprefixed pathnames.
  2. If you don't use domain-based routing, the cookie is now the source of truth for determining the locale in the middleware. Make sure that your hosting solution reliably returns the set-cookie header from the middleware (e.g. Vercel and Cloudflare are known to potentially strip this header (opens in a new tab) for cacheable requests).
  3. Alternate links are disabled in this mode since URLs might not be unique per locale. Due to this, consider including these yourself, or set up a sitemap that links localized pages via alternates.

Custom prefixes

If you'd like to customize the user-facing prefix, you can provide a locale-based mapping:

config.ts
import {LocalePrefix} from 'next-intl/routing';
 
export const locales = ['en-US', 'de-AT', 'zh'] as const;
 
export const localePrefix = {
  mode: 'always',
  prefixes: {
    'en-US': '/us',
    'de-AT': '/eu/at'
    // (/zh will be used as-is)
  }
} satisfies LocalePrefix<typeof locales>;

Note that:

  1. Custom prefixes are only visible to the user and rewritten internally to the corresponding locale. Therefore the [locale] segment will correspond to the locale, not the prefix.
  2. You might have to adapt your middleware matcher to match the custom prefixes.
Can I read the matched prefix in my app?

Since the custom prefix is rewritten to the locale internally, you can't access the prefix directly. However, you can extract details like the region from the locale:

import {useLocale} from 'next-intl';
 
function Component() {
  // Assuming the locale is 'en-US'
  const locale = useLocale();
 
  // Returns 'US'
  new Intl.Locale(locale).region;
}

The region must be a valid ISO 3166-1 alpha-2 country code (opens in a new tab) or a UN M49 region code (opens in a new tab). When passed to Intl.Locale, the region code is treated as case-insensitive and normalized to uppercase. You can also combine languages with regions where the language is not natively spoken (e.g. en-AT describes English as used in Austria).

Apart from the region, a locale can encode further properties (opens in a new tab), like the numbering system.

If you'd like to encode custom information in the locale, you can use arbitrary private extensions (opens in a new tab), denoted by the -x- prefix (e.g. en-US-x-usd). The Intl.Locale constructor ignores private extensions, but you can extract them from the locale string manually.

Localized pathnames

Many apps choose to localize pathnames, especially when search engine optimization is relevant, e.g.:

  • /en/about
  • /de/ueber-uns

Since you want to define these routes only once internally, you can use the next-intl middleware to rewrite (opens in a new tab) such incoming requests to shared pathnames.

config.ts
export const locales = ['en', 'de'] as const;
 
// The `pathnames` object holds pairs of internal and
// external paths. Based on the locale, the external
// paths are rewritten to the shared, internal ones.
export const pathnames = {
  // If all locales use the same pathname, a single
  // external path can be used for all locales
  '/': '/',
  '/blog': '/blog',
 
  // If locales use different paths, you can
  // specify each external path per locale
  '/about': {
    en: '/about',
    de: '/ueber-uns'
  },
 
  // Dynamic params are supported via square brackets
  '/news/[articleSlug]-[articleId]': {
    en: '/news/[articleSlug]-[articleId]',
    de: '/neuigkeiten/[articleSlug]-[articleId]'
  },
 
  // Static pathnames that overlap with dynamic segments
  // will be prioritized over the dynamic segment
  '/news/just-in': {
    en: '/news/just-in',
    de: '/neuigkeiten/aktuell'
  },
 
  // Also (optional) catch-all segments are supported
  '/categories/[...slug]': {
    en: '/categories/[...slug]',
    de: '/kategorien/[...slug]'
  }
} satisfies Pathnames<typeof locales>;

Note: Localized pathnames map to a single internal pathname that is created via the file-system based routing in Next.js. If you're using an external system like a CMS to localize pathnames, you'll typically implement this with a catch-all route like [locale]/[[...slug]].

๐Ÿ’ก

If you're using localized pathnames, you should use createLocalizedPathnamesNavigation instead of createSharedPathnamesNavigation for your navigation APIs.

How can I revalidate localized pathnames?

Depending on if a route is generated statically (at build time) or dynamically (at runtime), revalidatePath (opens in a new tab) needs to be called either for the localized or the internal pathname.

Consider this example:

app
โ””โ”€โ”€ [locale]
    โ””โ”€โ”€ news
        โ””โ”€โ”€ [slug]

โ€ฆ with this middleware configuration:

middleware.ts
import createMiddleware from 'next-intl/middleware';
 
export default createMiddleware({
  defaultLocale: 'en',
  locales: ['en', 'fr'],
  pathnames: {
    '/news/[slug]': {
      en: '/news/[slug]',
      fr: '/infos/[slug]'
    }
  }
});

Depending on whether some-article was included in generateStaticParams (opens in a new tab) or not, you can revalidate the route like this:

// Statically generated at build time
revalidatePath('/fr/news/some-article');
 
// Dynamically generated at runtime:
revalidatePath('/fr/infos/some-article');

When in doubt, you can revalidate both paths to be on the safe side.

See also: vercel/next.js#59825 (opens in a new tab)

How can I localize dynamic segments?

If you have a route like /news/[articleSlug]-[articleId], you may want to localize the articleSlug part in the pathname like this:

/en/news/launch-of-new-product-94812
/de/neuigkeiten/produktneuheit-94812

In this case, the localized slug can either be provided by the backend or generated in the frontend by slugifying the localized article title.

A good practice is to include the ID in the URL, allowing you to retrieve the article based on this information from the backend. The ID can be further used to implement self-healing URLs (opens in a new tab), where a redirect is added if the articleSlug doesn't match.

If you localize the values for dynamic segments, you might want to turn off alternate links and provide your own implementation that considers localized values for dynamic segments.

Domains

If you want to serve your localized content based on different domains, you can provide a list of mappings between domains and locales via the domains setting.

Examples:

  • us.example.com/en
  • ca.example.com/en
  • ca.example.com/fr
config.ts
import {DomainsConfig} from 'next-intl/routing';
 
export const locales = ['en', 'fr'] as const;
 
export const domains: DomainsConfig<typeof locales> = [
  {
    domain: 'us.example.com',
    defaultLocale: 'en',
    // Optionally restrict the locales available on this domain
    locales: ['en']
  },
  {
    domain: 'ca.example.com',
    defaultLocale: 'en'
    // If there are no `locales` specified on a domain,
    // all available locales will be supported here
  }
];

Note that:

  1. You can optionally remove the locale prefix in pathnames by changing the localePrefix setting. E.g. localePrefix: 'never' can be helpful in case you have unique domains per locale.
  2. If no domain matches, the middleware will fall back to the defaultLocale (e.g. on localhost).
How can I locally test if my setup is working?

Learn more about this in the locale detection for domain-based routing docs.

Docs

ย ยทย 

Examples

ย ยทย 

Blog

GitHub

ย ยทย 

Hosted onVercel