我构建了一个简单的项目,通过使用if和else语句保护网站的路由/页面,并使用函数withAuth()
放置每个页面,但我不确定这是否是使用nextjs保护路由的最佳方式,我注意到在保护路由或页面方面出现了延迟,比如2-3秒长,在页面重定向访问者或未注册用户之前,他们可以看到页面的内容。
有没有办法摆脱它或使请求更快,使未注册的用户不查看页面的内容?是否有更好的方法来保护nextjs框架中的某个路由?
代码
import { useContext, useEffect } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";
const withAuth = (Component) => {
const Auth = (props) => {
const { user } = useContext(AuthContext);
useEffect(() => {
if (!user) Router.push("/login");
});
return <Component {...props} />;
};
return Auth;
};
export default withAuth;
使用withAuth的示例
import React from "react";
import withAuth from "./withAuth";
function sample() {
return <div>This is a protected page</div>;
}
export default withAuth(sample);
发布于 2021-11-23 11:58:52
您可以使用户的authentication位于服务器端的上,如果用户登录,然后向他们展示保护路由的内容 else 将重定向到其他路由。有关mote信息,请参考此页。
在getServerSideProps
中,检查用户是否已登录
if (!data.username) {
return {
redirect: {
destination: '/accounts/login',
permanent: false,
},
}
}
下面是保护路由页面的完整示例
export default function SomeComponent() {
// some content
}
export async function getServerSideProps({ req }) {
const { token } = cookie.parse(req.headers.cookie)
const userRes = await fetch(`${URL}/api/user`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
const data = await userRes.json()
// does not allow access to page if not logged in
if (!data.username) {
return {
redirect: {
destination: '/accounts/login',
permanent: false,
},
}
}
return {
props: { data }
}
}
发布于 2022-08-08 11:27:57
带有自定义401页的
我们将首先定义自定义401页。
import React from "react"
const Page401 = () => {
return (
<React.Fragment>
//code of your customized 401 page
</React.Fragment>
)
}
export default Page401
现在,我们将更改共享的kiranr代码的一小部分。
export async function getServerSideProps({ req }) {
const { token } = cookie.parse(req.headers.cookie)
const userRes = await fetch(`${URL}/api/user`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
const data = await userRes.json()
// does not allow access to page if not logged in
if (!data.username) {
//THIS PART CHANGES
return {
props: {
unauthorized: true
}
}
//THIS PART CHANGES
}
return {
props: { data }
}
}
然后,我们将在我们的_app.js文件中检查这个“未经授权的”属性,如果它的值为真,则调用自定义的401页组件。
import Page401 from "../components/Error/Server/401/index";
const App = ({ Component, pageProps }) => {
//code..
if (pageProps.unauthorized) {
//if code block reaches here then it means the user is not authorized
return <Page401 />;
}
//code..
//if code block reaches here then it means the user is authorized
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
)
}
https://stackoverflow.com/questions/70078622
复制相似问题