簡體   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