Next.js 如果没有 cookie 则重定向

dom*_*kyi 11 regex cookies reactjs next.js

有没有办法仅在没有 cookie 的情况下将用户从结帐重定向到加入页面user_token。Next.js 允许仅设置字符串和未定义为value,但我需要验证没有 cookie:

  redirects: async () => [
    {
      source: '/checkout',
      has: [
        {
          type: 'cookie',
          key: 'user_token',
          value: '',
        },
      ],
      permanent: true,
      destination: '/join',
    },
  ],
Run Code Online (Sandbox Code Playgroud)

我尝试对空字符串使用正则表达式,但它不起作用:

  redirects: async () => [
    {
      source: '/checkout',
      has: [
        {
          type: 'cookie',
          key: 'user_token',
          value: '(^$)',
        },
      ],
      permanent: true,
      destination: '/join',
    },
  ],
Run Code Online (Sandbox Code Playgroud)

cyb*_*ain 0

我认为你遇到的问题是,你只是将其限制为一个空cookie。您必须检查路由内是否缺少 cookie 并res.redirect从那里发送 cookie ( https://nextjs.org/docs/api-routes/response-helpers )
并且:您确定要永久重定向吗?浏览器会缓存它,这些用户将来将被重定向,而无需向服务器发出请求。