我構建了一個簡單的專案,它通過使用 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);
uj5u.com熱心網友回復:
您可以在服務器端對用戶進行身份驗證,如果用戶已登錄,則向他們顯示受保護路由的內容,否則將他們重定向到其他路由。請參閱此頁面以獲取微粒資訊。
在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 }
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/368054.html
標籤:javascript 反应 安全 下一个.js
上一篇:Vaadin21Flow SpringSecurityOAuth2:找不到“oauth2/authorization/google”的路由
