本质上,我为我的Next.js应用程序中的两个页面(即 profile 和
dashboard
)创建了一个高阶组件,以防止未经授权的用户访问它们。
例如: pages / profile.js
<code>import withAuth from "../components/AuthCheck/index";
function Profile() {
return (
<>
<h1>Profile</h1>
</>
)
}
export default withAuth(Profile);
</code>
我的认证组件/HOC:
import { useRouter } from 'next/router'
import { useUser } from '../../lib/hooks'
import { PageLoader } from '../Loader/index'
const withAuth = Component => {
const Auth = (props) => {
const { isError } = useUser(); //My hook which is calling /api/user see if there is a user
const router = useRouter()
if (isError === 'Unauthorized') {
if (typeof window !== 'undefined' && router.pathname === '/profile' || router.pathname === 'dashboard') router.push('/login')
return <PageLoader />
}
return (
<Component {...props} />
);
};
if (Component.getInitialProps) {
Auth.getInitialProps = Component.getInitialProps;
}
return Auth;
};
export default withAuth;
现在的情况是,如果您在浏览器URL栏中输入/profile
或/dashboard
,在重定向之前会先看到页面闪烁一下。
你知道为什么会发生这种情况吗?