Protecting routes
Create an auth-protected.js
file:
You can protect routes using a authProtected
component. This component can be used
components/authProtected.js
import { useRouter } from 'next/router'
import { useAuthenticationStatus } from '@nhost/nextjs'
export function authProtected(Comp) {
return function AuthProtected(props) {
const router = useRouter()
const { isLoading, isAuthenticated } = useAuthenticationStatus()
if (isLoading) {
return <div>Loading...</div>
}
if (!isAuthenticated) {
router.push('/login')
return null
}
return <Comp {...props} />
}
}
Then wrap the Next.js page with authProtected
to protect the page so only signed-in users can access the page.
pages/index.js
import { authProtected } from 'components/authProtected'
function Index() {
return <div>Only signed-in users can see this page.</div>
}
export default authProtected(Index)