Search code examples
reactjstranslationnext.jsi18next

How to translate routes with NextJS and next-i18next?


I'm building a multiple language website with next.JS and the package next-i18next. It's going well, except one thing that I'm not sure what's the best approach. I want that my static routes will be translated too (not only the page content), for example:

example.com/en/home -> example.com/pt-br/inicio

example.com/en/contact -> example.com/pt-br/contato

I know I could create the directories (en/pt-br) and insert the pages inside of them (eg: home.js, contact.js etc inside "/en/" and inicio.js, contato.js etc inside "/pt-br/"), like this would be easy to define the language when the user access any of those pages, but I'd need to create 2 files with almost all the same content (eg: "/en/home" and "/pt-br/inicio"). So I'm wondering if there is any better solution for this?

Thanks!


Solution

  • Instead of duplicating the same page for multiple languages, which hurts build performance & won't scale if you need to support more then 5 langs, you can use Next.js rewrites.

    It was introduced in v9.5, and allows you to rewrite path to a specific page, in your example, you can create pages for the main lang, and all the secondary languages you can add support with rewrites. With a combination of i18n subpaths (which was introduced in v10) next will handle the locale part (/en/ / /pt-br/).

    For example: your pages folder will contain 2 pages, home & contact.

    // next.config.js
    
    module.exports = {
      i18n: {
        locales: ['en', 'pt-br'],
        defaultLocale: 'en',
      },
    
      async rewrites() {
        return [
          {
            source: '/inicio', // automatically handles all locales
            destination: '/home', // automatically passes the locale on
          },
          {
            source: '/contato', 
            destination: '/contact', 
          }
        ]
      },
    }
    

    For more info check Rewrites with i18n support article.