'How to enforce i18n locale slugs and achieve i18n consistency upon reload in Next.js?

I'm using next-translate. By default, my routes are recognized as follows:

/about         <---
/de/about
/es/about

but I'd like to enforce a locale for all paths:

/en/about      <---
/de/about
/es/about

Here's my config:

next.config.js

const nextTranslate = require('next-translate');

module.exports = nextTranslate({
    ...
    i18n: {
        localeDetection: false,
        locales: ['en', 'de', 'es'],
        defaultLocale: 'en',
    }
});

i18n.js

module.exports = {
    locales: ['en', 'de', 'es'],
    defaultLocale: 'en',
    pages: {
        '*': ['common']
    },
    interpolation: {
        prefix: '${',
        suffix: '}',
    },
    loadLocaleFrom: (locale, namespace) =>
        import(`./translations/${locale}/${namespace}`).then((m) => m.default),
}

Note that I also have a lang change component that persists the NEXT_LOCALE cookie. As such, I would expect that when I access /about and my NEXT_LOCALE cookie had previously been set to de, the router would redirect me to /de/about. But it does not. It stays at /about and rewrites the cookie to en...

Here's current pages folder structure:

...
pages/
  _app.tsx
  _document.tsx
  about.tsx
  ...

Do I need to restructure it to this?

pages/
  _app.tsx
  _document.tsx
  [lang]/         <---
    about.tsx
    ...

If so, what would be the next step?

  • Parse the preferred locale through useRouter()
  • Parse the NEXT_LOCALE cookie
  • Parse the lang slug

and then decide which has higher precedence? Where should I do that? In _app.tsx / some HOC?

Do I need any rewrites or redirects in my next.config.js or should I handle these dynamically through Router.push?



Solution 1:[1]

You are using the buttons to either add or subtract 10 from the X and Y coordinates, and checking to see if the values are within the range of the screen size, but not taking into account that you are changing them 10 units at a time.
Think about what happens when getX() returns a number from 1 to 9 and you click the "left" button, where will your new X coordinate be?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GodJihyo