如何在 next.js 中创建私有路由?

poc*_*oca 4 next.js next-router

我想包装我的整个应用程序,以便除非用户登录,否则无法访问它。如果用户未登录,我设法将用户重定向到登录页面,但是,我仍然看到之前的私有路由闪现发生重定向。如何避免这种情况?

Nic*_*ick 7

由于 NextJS 是服务器端渲染的,因此您需要getServerSideProps在重定向之前检查身份验证或在前端显示加载指示器。

检查客户端认证

创建一个包装器组件并将其放入您的_app.js文件中。通过在用户仍在进行身份验证时显示加载组件,可以防止显示私有仪表板。请注意:因为 Next.js 是服务器端渲染的,所以 HTML 始终会在 JS 重新水合之前显示。这意味着,第一次绘制总是在重定向开始之前发生。

import { useRouter } from 'next/router'

export const AuthCheck = (props) => {
  const router = useRouter()
  const user = useUser() // 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('/sign-in')

  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)

检查认证服务器端

假设您已经设置了代码来检查身份验证服务器端,则可以使用此模式。注意:您需要将其添加到每个页面。getServerSideProps 不适用于 _app.js_document.js

export const getServerSideProps = async () => {
  const isAuthenticated = await checkAuthentication() // you need to implement this

  if (!isAuthenticated) {
    return {
      redirect: { destination: '/sign-in', permanent: false },
    }
  }
}
Run Code Online (Sandbox Code Playgroud)