程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Next.js withPageAuthRequired 和 getStaticProps大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Next.js withPageAuthrequired 和 getStaticProps?

开发过程中遇到Next.js withPageAuthrequired 和 getStaticProps的问题如何解决?下面主要结合日常开发的经验,给出你关于Next.js withPageAuthrequired 和 getStaticProps的解决方法建议,希望对你解决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。

大佬总结

以上是大佬教程为你收集整理的Next.js withPageAuthRequired 和 getStaticProps全部内容,希望文章能够帮你解决Next.js withPageAuthRequired 和 getStaticProps所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。