Skip to content

Protected Routes

Wrap any content that should only be visible to authenticated users:

import { RequireAuth } from "oidc-js-react";
function Dashboard() {
return (
<RequireAuth>
<h1>Dashboard</h1>
<p>Only visible when authenticated.</p>
</RequireAuth>
);
}

If the user is not authenticated, RequireAuth automatically redirects to the IdP login page.

import { BrowserRouter, Routes, Route } from "react-router-dom";
import { AuthProvider, RequireAuth } from "oidc-js-react";
function App() {
return (
<AuthProvider config={config}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/dashboard"
element={
<RequireAuth>
<Dashboard />
</RequireAuth>
}
/>
<Route
path="/settings"
element={
<RequireAuth>
<Settings />
</RequireAuth>
}
/>
</Routes>
</BrowserRouter>
</AuthProvider>
);
}

Show a custom loading state while authentication is being checked:

<RequireAuth fallback={<Spinner />}>
<Dashboard />
</RequireAuth>

By default, RequireAuth checks if the access token is expired on each render. If it is, it silently refreshes using the refresh token before rendering the children.

If the refresh fails (e.g., the refresh token was revoked), it redirects to login.

// Disable auto-refresh if you want to handle it manually
<RequireAuth autoRefresh={false}>
<Dashboard />
</RequireAuth>

When an unauthenticated user navigates to a protected route, RequireAuth saves the current URL and restores it after login. The user lands on the page they originally requested, not the home page.