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.
Installation
Section titled “Installation”npm install oidc-js-preactimport { RequireAuth } from "oidc-js-preact";
function ProtectedPage() { return ( <RequireAuth fallback={<div>Loading...</div>}> <h1>Protected Content</h1> </RequireAuth> );}| Prop | Type | Default | Description |
|---|---|---|---|
children | ComponentChildren | required | Content to render when authenticated |
fallback | ComponentChildren | 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 RequireAuth renders:
- 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
With Preact Router
Section titled “With Preact Router”import Router from "preact-router";import { RequireAuth } from "oidc-js-preact";
function App() { return ( <AuthProvider config={config}> <Router> <Home path="/" /> <ProtectedRoute path="/dashboard" /> </Router> </AuthProvider> );}
function ProtectedRoute() { return ( <RequireAuth fallback={<Spinner />}> <Dashboard /> </RequireAuth> );}