Alexandre Paiva
Alexandre Paiva

Reputation: 1553

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!

Upvotes: 20

Views: 6578

Answers (3)

Daher
Daher

Reputation: 1441

For the newest NextJS version (right now 12.1.6) you ould use this package https://www.npmjs.com/package/next-translate-routes

To build a fully internationalized website, one need to translate url segments: it is important for UX and SEO. For now, Next only ship with locale prefixes (see Next.js internationalized routing doc).

The next-routes package allow fully internationalized routing but it is no longer maintained, and it is designed without the latest Next api, such as internationalized routing, new data fetching methods, automatic static optimization.

Upvotes: 0

felixmosh
felixmosh

Reputation: 35573

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.

Upvotes: 8

Phat Tran
Phat Tran

Reputation: 3910

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

Upvotes: 0

Related Questions