fua*_*z98 7 authentication url-routing reactjs next.js
我对 next.js 中的受保护路由有点困惑。
首先,我不想使用任何服务器端渲染。我想通过静态导出next export。那么,如何实现客户端保护路由呢?
假设我有一个具有基本JWT身份验证的后端服务器。如何使某些路由免受特定用户的影响并在/login页面中重定向它们?
由于您想要通过静态导出创建受保护的路由,因此您需要在浏览器中执行所有操作。
为此,我们将创建一个包装器AuthCheck组件。
有关的:
为了验证 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)