Skip to main content

Protecting routes

Create an auth-protected.js file:

You can protect routes using a authProtected component. This component can be used

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) {
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.

import { authProtected } from 'components/authProtected'

function Index() {
return <div>Only signed-in users can see this page.</div>

export default authProtected(Index)