poc*_*oca 4 next.js next-router
我想包装我的整个应用程序,以便除非用户登录,否则无法访问它。如果用户未登录,我设法将用户重定向到登录页面,但是,我仍然看到之前的私有路由闪现发生重定向。如何避免这种情况?
由于 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)
| 归档时间: |
|
| 查看次数: |
7425 次 |
| 最近记录: |