[英]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 的方法
您必须执行两个步骤
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),
},
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.