Skip to main content

Protecting routes

React Router

You can protect routes by creating a wrapper component (ProtectedRoute) and use that component to make sure the user is authenticated (signed-in) before seeing the component that is protected.

This means you can have certain parts of your app only available for signed-in users.

info

This example uses React Router v6 for routing.

src/components/ProtectedRoute.js
import { useAuthenticationStatus } from '@nhost/react'
import { Navigate, Outlet, useLocation } from 'react-router-dom'

export function ProtectedRoute() {
const { isAuthenticated, isLoading } = useAuthenticationStatus()
const location = useLocation()

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

if (!isAuthenticated) {
return <Navigate to="/sign-in" state={{ from: location }} replace />
}

return <Outlet />
}

The ProtectedRoute component uses the useAuthenticationStatus hook to get the authentication status of the user.

If the user is not authenticated (not signed-in), the user is redirected to /sign-in. Otherwise, the child route element is rendered for the signed-in user.

Finally, we use a layout route in App.js to wrap the ProtectedRoute component around the routes we want to protect:

src/App.js
import { NhostReactProvider } from '@nhost/react'
import { BrowserRouter, Route, Routes } from 'react-router-dom'

import { ProtectedRoute } from './components/ProtectedRoute'
import { nhost } from './lib/nhost'
import Dashboard from './pages/Dashboard'
import Home from './pages/Home'
import Login from './pages/Login'
import Profile from './pages/Profile'

export function App() {
return (
<NhostReactProvider nhost={nhost}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/dashboard" element={<ProtectedRoute />}>
<Route index element={<Dashboard />} />
<Route path="profile" element={<Profile />} />
</Route>
</Routes>
</BrowserRouter>
</NhostReactProvider>
)
}