next built-in i18n 以及 i18n router
https://nextjs.org/docs/advanced-features/i18n-routing#automatic-locale-detection

需求:本着提高用户体验,自动跳转到用户选择的语言

一开始对next文档没看全,计划用中间件处理每个请求,
当用户切换语言,写到cookie,然后用next middleware来根据cookie携带的locale,redirect到对应locale
image.png

后来看到next有默认cookie来处理这方面优先级

下面是根据文档的实践

Automatic Locale Detection

When a user visits the application root (generally /), Next.js will try to automatically detect which locale the user prefers based on the Accept-Language header and the current domain.

开启auto detection

image.png

浏览器语言优先级—初始en最高

image.png
image.png

切换浏览器语言优先级—zh最高

image.png
当访问默认地址,会307重定向到accept-language携带的最优先级的语言
image.png

利用设置特定cookie实现覆盖自动探测

Leveraging the NEXT_LOCALE cookie

Next.js supports overriding the accept-language header with a NEXT_LOCALE=the-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.

恢复浏览器en最高级

image.png

当用户切换locale时写到NEXT_LOCALE cookie中

image.png
切换到zh
image.png

访问默认主页,根据cookie重定向到cookie设定的zhimage.png

but 实际测试,当cookie为defautl locale,却并不能覆盖其他locale

比如 默认是en,cookie也写入en,当访问/zh/xxx, 正常访问到zh,不会根据cookie重定向