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

sbdsn5lh  于 2023-05-12  发布在  其他
关注(0)|答案(2)|浏览(140)

有没有一种方法可以将用户从结帐页面重定向到加入页面,如果没有cookie user_token。Next.js只允许将字符串和undefined设置为value,但我需要验证没有cookie:

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

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

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

tgabmvqs1#

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

91zkwejq

91zkwejq2#

从nextjs版本12.3.3开始(我想),我们可以在nextjs redirects配置上使用**“missing”**属性:

// next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  async redirects() {
    return [
      // if the cookie `user_token` is present,
      // this redirect will NOT be applied
      {
        source: "/checkout",
        missing: [
          {
            type: "cookie",
            key: "user_token",
          },
        ],
        permanent: false,
        destination: "/join",
      },
    ];
  },
};

module.exports = nextConfig;

文档

相关问题