我构建了一个简单的项目,通过使用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 ;
};
return Auth;
};
export default withAuth;
import React from "react";
import withAuth from "./withAuth";
function sample() {
return This is a protected page;
}
export default withAuth(sample);
发布于 2021-11-25 16:08:21
显然,对于我来说,来自@context/auth
的D1
是一个黑匣子,所以我无法知道是否有服务器端的功能。但是,如果您能够检索会话服务器端,那么使用Next.js,如果没有找到用户,可以使用getServerSideProps
重定向到/login
。这将阻止用户在页面上看到您提到的任何受保护的内容。
例如:
// pages/myPage.js
import { getUser } from "@context/auth";
export async function getServerSideProps(context) {
const { user } = await getUser();
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
return {
props: { user },
};
}
const MyPage = ({ user }) => {
return This is a protected page;
};
export default MyPage;
通常,在客户端(如果您无法完成此服务器端),我认为避免使用更高级的组件模式将提高可读性。我会创作一个简单的作文,如下所示:
import { useContext, useEffect, useState } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";
const Authorised = ({ children }) => {
const { user } = useContext(AuthContext);
useEffect(() => {
if (!user) Router.push("/login");
}, [user]);
if (!user) {
return null;
}
return children;
};
const Sample = () => {
This is protected content
};
由于您提到了延迟(在重定向之前?),我建议您呈现一个加载组件,而不是null
,以获得更好的用户体验,直到检索到用户会话。
如果您还没有读过Next.js关于身份验证的文档,我认为也是值得的。
https://codereview.stackexchange.com/questions/270263
复制相似问题