gor*_*nay 9 authentication reactjs 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;
Run Code Online (Sandbox Code Playgroud)
const AdminHome = () => {
return ();
};
export default withAuth(AdminHome);
Run Code Online (Sandbox Code Playgroud)
jul*_*ves 21
Based on the answer from Create a HOC (higher order component) for authentication in Next.js, you can create a re-usable higher-order function for the authentication logic.
If the user data isn't present it'll redirect to the login page. Otherwise, the function will continue on to call the wrapped getServerSideProps function, and will return the merged user data with the resulting props from the page.
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
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
You can then use it on the AdminHome page to wrap the getServerSideProps function.
const AdminHome = ({ data }) => {
return ();
};
export const getServerSideProps = withAuth(context => {
// Your normal `getServerSideProps` code here
return { props: {} };
});
export default AdminHome;
Run Code Online (Sandbox Code Playgroud)
If you'd rather have the authentication done on the client, you can create a higher-order component that wraps the component you want to protect.
const withAuth = (Component) => {
const AuthenticatedComponent = () => {
const router = useRouter();
const [data, setData] = useState()
useEffect(() => {
const getUser = async () => {
const response = await fetch('http://localhost:4000/user/me');
const userData = await response.json();
if (!userData) {
router.push('/admin/login');
} else {
setData(userData);
}
};
getUser();
}, []);
return !!data ? <Component data={data} /> : null; // Render whatever you want while the authentication occurs
};
return AuthenticatedComponent;
};
Run Code Online (Sandbox Code Playgroud)
You can then use it to wrap the AdminHome component directly.
const AdminHome = () => {
return ();
};
export default withAuth(AdminHome);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19346 次 |
| 最近记录: |