Blog>
Snippets

Localized Route Patterns with i18n Support

Explain how to configure internationalized routing in Next.js 14 using next.config.js and how to utilize localized routes in your application.
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'es'],
    defaultLocale: 'en',
    localeDetection: false,
  },
  async rewrites() {
    return [
      // Define locale-specific rewrites here
      // Example: a rewrite for the about page in French
      {
        source: '/about',
        destination: '/fr/about',
        locale: false,
      },
    ];
  },
};
This is a `next.config.js` configuration for i18n routing. It specifies supported locales, sets 'en' as the default, disables automatic locale detection, and includes a custom rewrite rule for the about page for French language, which is accessible via '/about' path regardless of the actual locale.
import { useRouter } from 'next/router';

function MyApp({ Component, pageProps }) {
  const router = useRouter();

  const changeLanguage = (lang) => {
    const regex = new RegExp(`^/(${router.locales.join('|')})`);
    router.push(router.asPath.replace(regex, `/${lang}`), undefined, { locale: lang });
  };

  // Usage example: <button onClick={() => changeLanguage('fr')}>French</button>

  return <Component {...pageProps} />;
}

export default MyApp;
This is a code snippet from a custom `_app.js` file in a Next.js application. It uses the 'useRouter' hook to access router properties and defines a function 'changeLanguage' that replaces the current locale in the URL with the chosen one. The example shows how to use a button to switch to French.