[英]How can I use Next.js redirects?
there.那里。 I want to configure the first screen as a login page, However, after logging in. we want to prevent the user from going to the login page after confirming the login with the cookie value, The configuration file is as below?我想配置首屏为登录页面,但是登录后我们想阻止用户通过cookie值确认登录后进入登录页面,配置文件如下? and how can I solve it?我该如何解决?
next.config.js下一步.config.js
module.exports = {
async redirects() {
return [
{
source: "/",
destination: "/login",
permanent: false,
has: [
{
type: "cookie",
key: "authorized",
value: "access_token",
},
],
},
];
},
};
This doesn't look possible to me, since in the config we only can have static values, and authtoken will change for every login, UI side redirection must be handled from separate AuthContext like we do with react apps.这在我看来是不可能的,因为在配置中我们只能有 static 个值,并且每次登录都会更改 authtoken,UI 端重定向必须从单独的 AuthContext 处理,就像我们对 React 应用程序所做的那样。
is having one more cookie like 'authorized' and it will have value let say true of false.还有一个像“授权”这样的 cookie,它将具有价值,可以说是真还是假。 So we can check for 'authorized' is it has value 'true', next.config is below for the same.所以我们可以检查“授权”是否具有值“真”,下面的 next.config 也是一样的。
Reference: https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching参考: 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',
},
],
},
]
},
}
A more robust and controllable approach would be using something like nextAuth一种更健壮和可控的方法是使用类似nextAuth 的方法
You would have to follow two steps您必须执行两个步骤
router.push
on client and getInitialProps
with a 302 on the server side为了涵盖服务器端和客户端场景(用户直接在登录页面上登录,同时实现这两个),您可以有条件地在客户端使用router.push
重定向,在服务器端使用 302 getInitialProps
ie Using nextAuth即使用 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
}
Serverside服务器端
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),
},
}
}
see example here - https://stackoverflow.com/a/69418553/13749957在这里查看示例 - https://stackoverflow.com/a/69418553/13749957
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.