我正在开发一个应用程序,我们有公共和管理路由,在我们过去的 CRA 应用程序中,我们使用了自定义路由元素,但我们在 nextjs 中没有……我们有很多公共页面,我们有 20 个私人页面/路线。
在nextjs中处理受保护的认证路由和公共路由的最佳方法是什么?
非常感谢!最好的事物
我想创建基本的 Next.js HOC 进行身份验证。我搜索过但没有弄清楚。
我的 Next.js 应用程序中有一个管理页面。我想从中获取数据http://localhost:4000/user/me,并且该 URL 返回我的用户。如果用户数据返回,则必须渲染组件。如果数据没有返回,我想重定向到该/admin/login页面。
我尝试了这段代码,但没有成功。我该如何解决这个问题?我也可以用useSWR代替 吗fetch?
const withAuth = (Component, { data }) => {
if (!data) {
return {
redirect: {
destination: "/admin/login",
},
};
}
return Component;
};
withAuth.getInitialProps = async () => {
const response = await fetch("http://localhost:4000/user/me");
const data = await response.json();
return { data };
};
export default withAuth;
Run Code Online (Sandbox Code Playgroud)
const AdminHome = () => {
return ();
};
export default withAuth(AdminHome);
Run Code Online (Sandbox Code Playgroud)