发布
社区首页 >问答首页 >基于Next.js next.config.js中的标头或cookie进行重定向

基于Next.js next.config.js中的标头或cookie进行重定向
EN

Stack Overflow用户
提问于 2021-07-24 01:52:06
回答 1查看 501关注 0票数 2

我们使用Next.js,并希望根据浏览器Accept-Language头将所有路径(不仅仅是根路径)路由到基于区域设置的路径。但是,如果用户设置了他们的区域,我们将设置一个cookie,首先需要检查该cookie以尊重用户的首选项。

因此,我们需要检查cookie,如果没有cookie,请尝试基于浏览器语言头的重定向。我们使用ISG仅限于服务器端的next.config.js重定向。

根据文档,这应该可以工作,但由于我们使用的是ISG,我们需要在next.config.js重定向函数中执行此操作。

我们已经尝试了这个解决方案,但是它不起作用(我们得到了无限的重定向作为cookie和头匹配):

代码语言:javascript
代码运行次数:0
复制
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')];
  },
});
EN

回答 1

Stack Overflow用户

发布于 2021-12-01 15:01:09

我已经设法使用_app.js实现了这一点

_app.js中添加getInitialProps

它检查请求中的cookie,使用ctx.locale获取当前区域设置,我的默认区域设置是en-IN,因此如果targetLocale匹配默认区域设置,它会将一个空字符串设置为targetLocale,然后使用header进行重定向。

除此之外,我们不必使用localeDetection,因为我们可以自己处理。

代码语言:javascript
代码运行次数:0
复制
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来处理第一次使用的用户时,我会显示模式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68503312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档