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

fua*_*z98 7 authentication url-routing reactjs next.js

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

首先,我不想使用任何服务器端渲染。我想通过静态导出next export。那么,如何实现客户端保护路由呢?

假设我有一个具有基本JWT身份验证的后端服务器。如何使某些路由免受特定用户的影响并在/login页面中重定向它们?

Nic*_*ick 6

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

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

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

有关的:

如何在 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

export default MyApp
Run Code Online (Sandbox Code Playgroud)

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

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