2

我们正在使用 Next.js,并希望根据浏览器标头将所有路径(不仅仅是根路径)路由到基于区域设置的路径Accept-Language。但是,如果用户设置他们的区域,我们将设置一个 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')];
  },
});
4

1 回答 1

0

我已经设法使用_app.js
Add getInitialPropsinside_app.js
它检查cookie内部请求,使用获取当前语言环境ctx.locale,我的默认语言环境是en-IN这样,如果targetLocale与默认语言环境匹配,它将一个空字符串设置为targetLocale,然后使用标头重定向。
除此之外,我们不必使用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 时,我会显示模态。

于 2021-12-01T15:01:09.373 回答