如何使用 Next.js 重定向?

How can I use Next.js redirects?

有! 我想将第一个屏幕配置为登录页面。 但是,在登录后,我们想阻止用户通过cookie值确认登录后,再去登录页面。 配置文件如下,请问如何解决?

next.config.js

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

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

的方法

您必须执行两个步骤

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

即使用 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 获取 cookie,将其声明为提供者

在此处查看示例 -

这对我来说似乎不可能,因为在配置中我们只能有静态值,并且每次登录都会更改 authtoken,UI 侧重定向必须像我们一样从单独的 AuthContext 处理反应应用程序。

上述方法的另一种选择

又多了一个像 'authorized' 这样的 cookie,它的值可以说是真还是假。所以我们可以检查 'authorized' 是否具有值 'true',下面的 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',
          },
        ],
      },
    ]
  },
}