问题描述
我正在开发一个应用程序,我们有公共和管理路由,在我们过去的 CRA 应用程序中,我们使用了自定义路由元素,但我们在 nextjs 中没有……我们有很多公共页面,并且我们有 20 个私人页面/路由.
I'm working on a app that we have public and admin routes, in our past CRA app we've used custom routes elements, but we dont have thins in nextjs... We have a lot of public pages, and we have 20 private pages/routes.
在 nextjs 中处理受保护的认证路由和公共路由的最佳方法是什么?
Whats is the best way to deal with protected autenticated routes and public routes in nextjs?
非常感谢!最好的
推荐答案
我个人一直为此使用 HOC(高阶组件).
I personally have been using HOCs (higher-order component) for this.
这是一个示例身份验证 HOC:
Here is an example authentication HOC:
const withAuth = Component => {
const Auth = (props) => {
// Login data added to props via redux-store (or use react context for example)
const { isLoggedIn } = props;
// If user is not logged in, return login component
if (!isLoggedIn) {
return (
<Login />
);
}
// If user is logged in, return original component
return (
<Component {...props} />
);
};
// Copy getInitial props so it will run as well
if (Component.getInitialProps) {
Auth.getInitialProps = Component.getInitialProps;
}
return Auth;
};
export default withAuth;
您可以将此 HOC 用于任何页面组件.下面是一个用法示例:
You can use this HOC for any page component.Here is an example of usage:
const MyPage = () => (
<> My private page</>
);
export default withAuth(MyPage);
如果需要,您可以通过角色检查(如公共、普通用户和管理员)扩展 withAuth HOC.
You can extend withAuth HOC with role checks like public, regular user and admin if needed.
这篇关于你如何处理 NextJS 应用程序中的公共和私有路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!