【问题标题】:How can you create a Private route in next.js?如何在 next.js 中创建私有路由?
【发布时间】:2021-06-18 00:45:06
【问题描述】:

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

【问题讨论】:

  • 是的@AndrewZheng 我尝试了这种方法,但由于某种原因,我仍然看到私人页面在重定向之前闪现
  • @poca 我总是使用 swr 来执行此操作,它会阻止渲染直到满足条件。我让用户通过 swr 身份验证并检查用户是否存在然后我重定向

标签: next.js next-router


【解决方案1】:

因为 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
}

然后在你的_app.js

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

export default MyApp

检查认证服务器端

假设您已经有代码设置来检查服务器端的身份验证,您可以使用此模式。注意:您需要将其添加到每个页面。 getServerSidePropsdoes not work with_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 },
    }
  }
}

【讨论】:

  • 谢谢尼克!,但在实施后我收到以下错误:'错误:找不到路由器实例。您应该只在应用程序的客户端内使用“next/router”。 err.sh/vercel/next.js/no-router-instance'
  • 你是对的,忘记添加检查以查看代码是否在浏览器中运行。现在更新答案。
猜你喜欢
  • 1970-01-01
  • 2023-02-08
  • 2020-11-17
  • 2022-11-12
  • 2022-11-12
  • 2022-01-17
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多