[英]Auth0 breaks Next.js — pageProps are empty when page is wrapped with withPageAuthRequired HOC
[英]How to create HOC for auth in Next.js?
我想创建基本的 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;
const AdminHome = () => {
return ();
};
export default withAuth(AdminHome);
您是否使用任何 JS 库进行身份验证? 这是auth0 文档,可能会给您一些想法。
根据Create a HOC (higher order component) for authentication in Next.js 中的答案,您可以为身份验证逻辑创建可重用的高阶 function。
如果用户数据不存在,它将重定向到登录页面。 否则,function 将继续调用包装的getServerSideProps
function,并将从页面返回合并的用户数据和生成的道具。
export function withAuth(gssp) {
return async (context) => {
const response = await fetch('http://localhost:4000/user/me');
const data = await response.json();
if (!data) {
return {
redirect: {
destination: '/admin/login'
}
};
}
const gsspData = await gssp(context); // Run `getServerSideProps` to get page-specific data
// Pass page-specific props along with user data from `withAuth` to component
return {
props: {
...gsspData.props,
data
}
};
}
}
然后,您可以在AdminHome
页面上使用它来包装getServerSideProps
function。
const AdminHome = ({ data }) => {
return ();
};
export const getServerSideProps = withAuth(context => {
// Your normal `getServerSideProps` code here
return { props: {} };
});
export default AdminHome;
如果您正在寻找 typescript 版本:
withAuth.ts
export function withAuth(gssp: GetServerSideProps): GetServerSideProps {
return async (context) => {
const { user } = (await getSession(context.req, context.res)) || {};
if (!user) {
return {
redirect: { statusCode: 302, destination: "/" },
};
}
const gsspData = await gssp(context);
if (!("props" in gsspData)) {
throw new Error("invalid getSSP result");
}
return {
props: {
...gsspData.props,
user,
},
};
};
}
主页.tsx
export const getServerSideProps = withAuth(async (context) => {
return { props: {} };
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.