Next.js中基于header或cookie的重定向.next.config.js



我们正在使用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')];
  },
});

我已经设法实现这使用_app.js
添加getInitialProps_app.js
它检查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来处理第一次用户时,我显示modal。

最新更新