简体   繁体   中英

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

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?

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

You can do it with middleware and NEXT_LOCALE cookie, when you change language you should set this cookie

document.cookie = `NEXT_LOCALE=${langugage};path=/`;

middleware.js

import { NextResponse } from "next/server";

export function middleware(request) {
  const localeCookie = request.cookies.get("NEXT_LOCALE");
  if (localeCookie !== undefined && request.nextUrl.locale !== localeCookie) {
    return NextResponse.redirect(new URL(`/${localeCookie}${request.nextUrl.pathname}`, request.url));
  }
}
export const config = { 
  matcher: ["/", "/about"], // paths on which middleware will work
};

https://nextjs.org/docs/advanced-features/i18n-routing#leveraging-the-next_locale-cookie

https://nextjs.org/docs/advanced-features/i18n-routing#prefixing-the-default-locale

https://nextjs.org/docs/advanced-features/middleware

https://nextjs.org/docs/messages/middleware-upgrade-guide

https://nextjs.org/docs/api-reference/next/server

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM