我们使用Next.js,并希望根据浏览器Accept-Language
头将所有路径(不仅仅是根路径)路由到基于区域设置的路径。但是,如果用户设置了他们的区域,我们将设置一个cookie,首先需要检查该cookie以尊重用户的首选项。
因此,我们需要检查cookie,如果没有cookie,请尝试基于浏览器语言头的重定向。我们使用ISG仅限于服务器端的next.config.js重定向。
根据文档,这应该可以工作,但由于我们使用的是ISG,我们需要在next.config.js
重定向函数中执行此操作。
我们已经尝试了这个解决方案,但是它不起作用(我们得到了无限的重定向作为cookie和头匹配):
const { i18n } = require('./next-i18next.config');
const withTM = require('next-transpile-modules')(['fitty', 'react-svg']); // pass the modules you would like to see transpiled
const handleLocaleRedirects = (path) => {
const result = [];
i18n.locales.forEach((locale) => {
i18n.locales.forEach((loc) => {
if (loc !== locale) {
result.push({
source: `/${locale}${path}`,
has: [
{
type: 'header',
key: 'accept-language',
value: `^${loc}(.*)`,
},
],
permanent: false,
locale: false,
destination: `/${loc}${path}`,
});
result.push({
source: `/${locale}${path}`,
has: [
{
type: 'cookie',
key: 'NEXT_LOCALE',
value: loc,
},
],
permanent: true,
locale: false,
destination: `/${loc}${path}`,
});
}
});
});
return result;
};
module.exports = withTM({
i18n,
reactStrictMode: true,
images: {
domains: [
'dxjnh2froe2ec.cloudfront.net',
'starsona-stb-usea1.s3.amazonaws.com',
],
},
eslint: {
// Warning: Dangerously allow production builds to successfully complete even if
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
async redirects() {
return [...handleLocaleRedirects('/:celebrityId')];
},
});
发布于 2021-12-01 15:01:09
我已经设法使用_app.js
实现了这一点
在_app.js
中添加getInitialProps
它检查请求中的cookie
,使用ctx.locale
获取当前区域设置,我的默认区域设置是en-IN
,因此如果targetLocale
匹配默认区域设置,它会将一个空字符串设置为targetLocale
,然后使用header进行重定向。
除此之外,我们不必使用localeDetection
,因为我们可以自己处理。
MyApp.getInitialProps = async ({ ctx }) => {
if (ctx.req) {
const rawCookies = ctx.req.headers.cookie
let locale = ctx.locale
const path = ctx.asPath
if (rawCookies != undefined) {
const cookies = cookie.parse(rawCookies)
let targetLocale = cookies['NEXT_LOCALE']
if (targetLocale != locale) {
if (targetLocale == 'en-IN') {
targetLocale = ''
} else {
targetLocale = '/' + targetLocale
}
ctx.res.writeHead(302, {
Location: `${targetLocale}${path}`
})
ctx.res.end()
}
}
}
return {}
}
除此之外,当没有名为NEXT_LOCALE
的cookie来处理第一次使用的用户时,我会显示模式。
https://stackoverflow.com/questions/68503312
复制相似问题