aralroca / next-translate-plugin

Next-translate plugin for i18n in Next.js 🌍 - Load page translations and use them in an easy way!
MIT License
30 stars 17 forks source link

Support Next.js 13 app-dir for server/client pages and server/client components #1

Closed aralroca closed 1 year ago

aralroca commented 1 year ago

Related with this issue https://github.com/aralroca/next-translate/issues/981 PR in next-translate: https://github.com/aralroca/next-translate/pull/982


Docs about this feature

Use Next 13 app directory

When it comes to server components and client components, it can be challenging to load the same thing on different pages. To simplify this process, we have extracted all the complexity using the next-translate-plugin.

Regarding translations:

If you use the "app" folder instead of the "pages" folder, the next-translate-plugin will automatically detect the change, and you won't need to touch any of the Next-translate configuration. The only difference is that the "pages" configuration property will reference the pages located within the "app" folder.

i18n.js

module.exports = {
  locales: ['en', 'ca', 'es'],
  defaultLocale: 'en',
  pages: {
    '*': ['common'],
    '/': ['home'], // app/page.tsx
    '/second-page': ['home'], // app/second-page/page.tsx
  },
}

By simply changing the "pages" folder to "app," you can consume translations within your pages using the useTranslation hook or the Trans component. You will still see the log (if enabled) to know which namespaces are loaded on each page, and everything else should be the same.

Regarding routing:

The routing is part of the core of Next.js (not from this library), but direct routing support is not yet available with the beta version of Next 13's app directory. As a workaround, Next.js recommends configuring it as described here:

The next-translate-plugin automatically detects the "lang" parameter. So, without any rewrite, you can test if your translations work by entering your page with the "lang" parameter. For example: /some-page?lang=en.

With this in mind, you can do any rewrite as described in the Next documentation, and if the final page has this parameter, everything should work without any additional manual changes. For example, if you rewrite /en-US/some-page to /some-page?lang=en-US, then the useTranslation will look for translations in en-US without needing to pass this parameter.