Next.js 客户端保护路由,无需服务器端渲染

时间:2021-06-10 08:30:32

标签: reactjs authentication next.js url-routing

我对 next.js 中的受保护路由有点困惑。

首先,我不想使用任何服务器端渲染。我想静态导出 通过np.int64。在这种情况下,我该如何实现客户端保护路由?

比如说,我有一个带有基本 JWT 身份验证的后端服务器。如何使某些路由免受某些用户的影响并在 next export 页面中重定向它们?

1 个答案:

答案 0 :(得分:1)

由于您想使用静态导出创建受保护的路由,因此您需要在浏览器中执行所有操作。

  1. 在浏览器中验证他们的 JWT
  2. 如果他们的 JWT 有效,则呈现页面(包括所有获取数据的请求)
  3. 如果他们的 JWT 无效,则重定向他们

为此,我们将创建一个包装器 AuthCheck 组件。

相关:

How can you create a Private route in next.js?

验证检查

为了验证 JWT,您可以使用任何您喜欢的方法,包括将其发送到 api 端点进行验证。虽然我不确定您是否可以将 Next.js api 端点与静态导出一起使用。

import { useRouter } from 'next/router'

export const AuthCheck = (props) => {
  const router = useRouter()
  const isJWTValid = useIsJWTValid() // you need to implement this. In this example, undefined means things are still loading, null means user is not signed in, anything truthy means they're signed in

  if (typeof window !== 'undefined' && user === null) router.push('/')

  if(!user) return <Loading /> // a loading component that prevents the page from rendering
   
  return props.children
}

然后您可以将其添加到您的 app.js。

const MyApp = ({ Component, pageProps }) => {
  return (
    <AuthCheck>
      <Component {...pageProps} />
    </AuthCheck>
  )
}

export default MyApp

或者,您也可以将其添加到任何单个页面。有了这个,您可能需要调试任何获取数据的时间。

export default const ProtectedPage = () => {
  return (
    <AuthCheck>
      <!-- contents of the page -->
    </AuthCheck>
  )
}