19
votes

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!

2
Did you find a solution? @Alexandre Paiva? - user1228739
The only possible way I can think of is using next-routes with next-i18next. - Allen Wong
I am facing the same problem. Have you found a solution? - Sodhi saab

2 Answers

8
votes

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.

0
votes

For workaround,

I created the component page as a separate module, then I import and export it back at the locale page folder. So I can reuse 1 component for multiple languages.

enter image description here

enter image description here

enter image description here