supporting libraries
@nhost/react-auth makes it easy to use authenticate with Nhost in your React app.

Install @nhost/react-auth and its dependencies:
$npm install @nhost/nhost-js @nhost/react-auth

@nhost/react-auth exports a React provider NhostAuthProvider that can handle authentication state in your app. Wrap this component around your whole App.
import React from 'react'
import ReactDOM from 'react-dom'
import { NhostClient } from '@nhost/nhost-js'
import { NhostAuthProvider } from '@nhost/react-auth'

import App from './App'

const nhost = new NhostClient({
  backendUrl: 'https://[app-subdomain]'

    <NhostAuthProvider nhost={nhost}>
      <App />

Now you can get the login state of the current user:
const { isLoading, isAuthenticated } = useNhostAuth()

console.log({ isLoading })
console.log({ isAuthenticated })

if (isLoading) {

if (!isAuthenticated) {
  console.log('User is not authenticated')

console.log('User is authenticated')

When using React Router with @nhost/react-auth, you can protect routes by creating an AuthGate component:
import { Redirect } from 'react-router-dom'
import { useNhostAuth } from '@nhost/react-auth'

export function AuthGate(children) {
  const { isLoading, isAuthenticated } = useNhostAuth()

  if (isLoading) {
    return <div>Loading...</div>

  if (!isAuthenticated) {
    return <Redirect to="/login" />

  return children

Then, in your React Router, wrap the AuthGate component around the routes you want to protect:
    <Route path="/login">
      <Login />
    <Route path="/" exact>
      <AuthGate> // <--- Use AuthGate component like this
        <div>My protected dashboard</div>

Create a auth-protected.js file:
import { useRouter } from 'next/router'
import { useNhostAuth } from '@nhost/react-auth'

export function authProtected(Comp) {
  return function AuthProtected(props) {
    const router = useRouter()
    const { isLoading, isAuthenticated } = useNhostAuth()

    if (isLoading) {
      return <div>Loading...</div>

    if (!isAuthenticated) {
      return null

    return <Comp {...props} />

Then wrap the Next.js page with authProtected to only allow signed in users to access the page.
import { authProtected } from '<some-path>/auth-protected'

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

export default authProtected(Index)