How to force Next.js to always redirect to a preferred user language?

Viewed 2575

Currently, Next.js makes a redirect to the user's language only from the root, so "/" becomes "/fr-FR". But if a user accesses for example "/profile" route, it won't redirect him to the "/fr-FR/profile".

Is there a way to force Next to do these kinds of redirects?

3 Answers

By default, Next.js automatically detects the user's preferred locale based on the Accept-Language header sent in the page request.

To override the locale from this header you can use the NEXT_LOCALE cookie.

This cookie can be set using a language switcher and then when a user comes back to the site it will leverage the locale specified in the cookie when redirecting from / to the correct locale location.

In your case, even if a user has the locale en in their Accept-Language header but a NEXT_LOCALE=fr-FR cookie is set, then when visiting /profile the user will be redirected to /fr-FR/profile until the cookie is removed or expired.


Check Storing selected language option in cookie/localSession for an example on how to store the NEXT_LOCALE cookie.

Check out this Page from the official NextJS Documentation:

Prefixing the Default Locale

It solves your problem by redirecting domain.com/example to domain.com/en/example

Sub-path Routing
Sub-path Routing puts the locale in the url path.

With the above configuration en-US, fr, and nl-NL will be available to be routed to, and en-US is the default locale. If you have a pages/blog.js the following urls would be available:

//next.config.js
module.exports = {
  i18n: {
    locales: ['en-US', 'fr', 'nl-NL'],
    defaultLocale: 'en-US',
  },
}

/blog
/fr/blog
/nl-nl/blog
The default locale does not have a prefix.

from Nextjs docs
Related