RequireAuth
RequireAuth is a guard component that ensures its children are only rendered when the user is authenticated. It handles token expiry and automatic refresh.
import { RequireAuth } from "oidc-js-react";
function ProtectedPage() { return ( <RequireAuth> <h1>Protected Content</h1> </RequireAuth> );}| Prop | Type | Default | Description |
|---|---|---|---|
children | ReactNode | required | Content to render when authenticated |
fallback | ReactNode | null | Shown while loading or redirecting |
autoRefresh | boolean | true | Auto-refresh expired tokens before redirecting to login |
loginOptions | LoginOptions | — | Options passed to actions.login() when redirecting |
Behavior
Section titled “Behavior”When a user navigates to a protected route:
- If still loading (discovery, callback), render
fallback - If authenticated with a valid token, render
children - If the token is expired and
autoRefreshistrue, attempt a silent refresh - If refresh succeeds, render
childrenwith the new token - If refresh fails (or no refresh token), redirect to the IdP login
Deep linking
Section titled “Deep linking”RequireAuth preserves the current URL when redirecting to login. After the user authenticates, they return to the page they originally requested.
// User visits /dashboard/settings while unauthenticated// → Redirected to IdP login// → After login, returned to /dashboard/settings<RequireAuth> <Settings /></RequireAuth>With React Router
Section titled “With React Router”import { Routes, Route } from "react-router-dom";import { RequireAuth } from "oidc-js-react";
<Routes> <Route path="/" element={<Home />} /> <Route path="/dashboard" element={ <RequireAuth fallback={<Spinner />}> <Dashboard /> </RequireAuth> } /></Routes>