【问题标题】:DRY way to authenticate several pages in Nextjs?在 Nextjs 中验证多个页面的 DRY 方法?
【发布时间】:2022-02-01 15:23:24
【问题描述】:

我知道在页面组件中我可以做类似的事情

if(!isAuthenticated){
    router.replace("/login")
  }

但是,如果我的 95% 的路线需要登录,那么最好的方法是什么?我查看了中间件,但因为它在服务器端运行,所以我无法访问应用程序状态。

我是 React 和 Nextjs 的新手。我来自有角度的背景,这将通过路由保护来解决,Nextjs 中是否有类似的东西?

【问题讨论】:

  • 可能是 MustBeAuthenticated layout 组件。
  • 查看 react 中的协调概念——尝试按照 Brian 的建议使用根布局组件。您可以以强类型的方式从客户端上的服务器端访问数据(假设您使用的是来自 Angular 的打字稿)。从下一个导入GetStaticPropsContextGetServerSidePropsContext 以及GetStaticPropsResultGetServerSidePropsResult。然后,在任何非_*页面的默认导出中,您可以通过使用另一个下一个导入InferGetStaticPropsType<typeof getStaticProps>InferGetServerSidePropsType<typeof getServerSideProps>来推断服务器道具
  • 这是否回答了您的问题(检查客户端解决方案):How to create HOC for auth in Next.js??

标签: reactjs next.js


【解决方案1】:

你应该使用Middleware

如果您的中间件是在/pages/_middleware.js 中创建的,它将在/pages 目录中的所有路由上运行。

更多信息请阅读official page

js的解决方案

import { NextResponse } from 'next/server'

export async function middleware(req, ev) {
    // req: contains request information

    if (!isAuthenticated()) {
        return NextResponse.redirect('/login');
    }
    return NextResponse.next();
}

ts的解决方案

import type { NextFetchEvent, NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

export function middleware(req: NextRequest, ev: NextFetchEvent) {
    if (!isAuthenticated()) {
        return NextResponse.redirect('/login');
    }
    return NextResponse.next();
}

【讨论】:

  • 中间件在服务器上运行,无权访问应用状态
【解决方案2】:

您可以将您的身份验证代码放在高阶组件中,并使用此组件包装您的所有组件。您可以在此处找到完整的详细信息 - https://reactjs.org/docs/higher-order-components.html

高阶组件 (HOC) 是 React 中的一种高级技术 重用组件逻辑。 HOC 本身并不是 React API 的一部分。 它们是从 React 的组合性质中出现的一种模式。

使用 HOC 进行身份验证示例 - https://www.codementor.io/@sahilmittal/using-higher-order-components-for-authenticated-routing-i1hcp6pc6

<Route path="">
    <Route path="/signin" component={SignIn} />
    ...
    <Route path="/app" component={requiresAuth(App)}>
      <Route name="dashboard" path="dashboard" component={Dashboard} />
      <Route name="profile" path="user-profile" component={UserProfile} />
    </Route>
    ...
  </Route>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 2017-05-24
    • 2021-01-29
    • 2015-08-10
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多