繁体   English   中英

如何使用 Next.js 重定向?

[英]How can I use Next.js redirects?

那里。 我想配置首屏为登录页面,但是登录后我们想阻止用户通过cookie值确认登录后进入登录页面,配置文件如下? 我该如何解决?

下一步.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: "/",
        destination: "/login",
        permanent: false,
        has: [
          {
            type: "cookie",
            key: "authorized",
            value: "access_token",
          },
        ],
      },
    ];
  },
};

这在我看来是不可能的,因为在配置中我们只能有 static 个值,并且每次登录都会更改 authtoken,UI 端重定向必须从单独的 AuthContext 处理,就像我们对 React 应用程序所做的那样。

上述方法的另一种选择

还有一个像“授权”这样的 cookie,它将具有价值,可以说是真还是假。 所以我们可以检查“授权”是否具有值“真”,下面的 next.config 也是一样的。

参考: https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching

{
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: '/',
        destination: '/login',
        permanent: true,
        has: [
          {
            type: 'cookie',
            key: 'authorized',
            value: 'false',
          },
        ],
      },
    ]
  },
}

一种更健壮和可控的方法是使用类似nextAuth 的方法

您必须执行两个步骤

  1. 为了涵盖服务器端和客户端场景(用户直接在登录页面上登录,同时实现这两个),您可以有条件地在客户端使用router.push重定向,在服务器端使用 302 getInitialProps

即使用 nextAuth


import { useSession, getSession } from "next-auth/react"

export default function Page() {
  const { data: session, status } = useSession()

  if (status === "loading") {
    return <p>Loading...</p>
  }

  if (status === "unauthenticated") {
    return <p>Access Denied</p>
  }

// Do a router.push here  
}

服务器端

import { useSession, getSession } from "next-auth/react"

export default function Page() {
  const { data: session } = useSession()

  if (typeof window === "undefined") return null

  if (session) {
    // do a 302 redirect, using ctx.resShead via getInitialprops    


  return <p>Access Denied</p>
}

export async function getServerSideProps(context) {
  return {
    props: {
      session: await getSession(context),
    },
  }
}

  1. 为了让 nextAuth 获得 cookies,将其声明为提供者

在这里查看示例 - https://stackoverflow.com/a/69418553/13749957

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM