【问题标题】:Next.js withPageAuthRequired with getStaticPropsNext.js withPageAuthRequired 和 getStaticProps
【发布时间】:2023-04-03 18:50:01
【问题描述】:

根据文档@auth0/nextjs-auth0,我们可以使用withPageAuthRequired 在需要登录的页面上触发登录屏幕。

短变体:export const getServerSideProps = withPageAuthRequired();

但是,如果我需要在构建时使用getStaticProps 进行预渲染页面而不能与getServerSideProps 一起使用,该怎么办?有什么方法可以在请求静态生成页面时使用withPageAuthRequired

现在我在客户端使用双重检查来检查身份验证。但我宁愿使用服务器端检查,就像我在其他页面上使用的那样。

附:也可以在客户端使用withPageAuthRequired。这个不适合我用

【问题讨论】:

    标签: next.js auth0 getstaticprops


    【解决方案1】:

    由于getStaticProps() 用于构建静态页面(即在请求时没有服务器端逻辑/呈现),因此必须在客户端进行身份验证检查和重定向到登录。

    您可以通过在静态资源前面添加代理(例如,使用 Lambda@Edge)来获得您想要的行为,尽管我对这种方法还不是很熟悉。


    从您的问题来看,您似乎已经熟悉如何在客户端进行检查/重定向,但是为了将来遇到这篇文章的其他人的利益:

    要在客户端获取用户信息,请将<UserProvider> 添加到您的应用,并在客户端组件中调用useUser() 挂钩。

    docs:

    UserProvider 组件包装您的pages/_app.js 组件:

    // pages/_app.js
    import React from 'react';
    import { UserProvider } from '@auth0/nextjs-auth0';
    
    export default function App({ Component, pageProps }) {
      return (
        <UserProvider>
          <Component {...pageProps} />
        </UserProvider>
      );
    }
    

    您现在可以通过检查 定义了useUser() 钩子返回的user 对象。你可以 还可以从您的前端层登录或注销您的用户 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

    【讨论】:

    • 我了解下一个 js 静态生成是如何工作的。我的想法是使用自定义服务器从请求中检测会话或 cookie 以检查身份验证状态并基于此返回页面或重定向到登录。我想知道有没有人有过这样的经历。附言我不使用客户端检查,因为我们得到的是 jsx 而不是 SSG 创建的 html 页面。
    猜你喜欢
    • 2021-08-02
    • 2021-10-17
    • 1970-01-01
    • 2020-12-18
    • 2023-03-19
    • 2021-12-30
    • 2021-03-16
    • 2020-10-29
    • 2021-06-22
    相关资源
    最近更新 更多