如何解决Next.js withPageAuthRequired 和 getStaticProps
根据文档 @auth0/nextjs-auth0,我们可以使用 withPageAuthrequired
在需要登录的页面上触发登录屏幕。
短变体:export const getServerSideProps = withPageAuthrequired();
但是如果我需要在构建时使用 getStaticProps
进行预渲染页面而不能与 getServerSideProps 一起使用,该怎么办?有没有办法在请求静态生成的页面上使用 withPageAuthrequired
?
现在我在客户端使用双重检查来检查身份验证。但我更愿意像在其他页面上一样使用服务器端检查。
附言也可以在客户端使用 withPageAuthrequired
。这不适合我使用
解决方法
由于 getStaticProps()
用于构建静态页面(即,在请求时没有服务器端逻辑/呈现),因此必须在客户端进行身份验证检查和重定向到登录。
您可能能够通过在静态资源前添加代理(例如,使用 Lambda@Edge)来获得您想要的行为,尽管我对这种方法还不是很熟悉。
从您的问题来看,您似乎已经熟悉如何在客户端进行检查/重定向,但为了将来遇到此帖子的其他人的利益:
要在客户端获取用户信息,请向您的应用添加 <UserProvider>
,并在客户端组件中调用 useUser()
挂钩。
见docs:
用 pages/_app.js
组件包裹您的 UserProvider
组件:
// pages/_app.js
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';
export default function App({ Component,pageProps }) {
return (
<UserProvider>
<Component {...pageProps} />
</UserProvider>
);
}
您现在可以通过检查用户是否通过身份验证来确定
user
钩子返回的 useUser()
对象已定义。你可以
还可以从您的前端层登录或注销您的用户
Next.js 应用程序通过将它们重定向到适当的
自动生成的路线:
// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';
export default function Index() {
const { user,error,isLoading } = useUser();
if (isLoading) return <div>Loading...</div>;
if (error) return <div>{error.message}</div>;
if (user) {
return (
<div>
Welcome {user.name}!
<a href="/api/auth/logout">Logout</a>
</div>
);
}
return <a href="/api/auth/login">Login</a>;
}
有关其他综合示例,请参阅 EXAMPLES.md 文档。
在客户端使用 withPageAuthRequired()
的替代方法:
import React from 'react';
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
import Layout from '../components/layout';
export default withPageAuthRequired(function Profile({ user }) {
return (
<Layout>
<h1>Profile</h1>
<h4>Profile</h4>
<pre data-testid="profile">{JSON.stringify(user,null,2)}</pre>
</Layout>
);
});
链接自 additional examples。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。