Skip to content

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.

Terminal window
npm install oidc-js-preact
import { RequireAuth } from "oidc-js-preact";
function ProtectedPage() {
return (
<RequireAuth fallback={<div>Loading...</div>}>
<h1>Protected Content</h1>
</RequireAuth>
);
}
PropTypeDefaultDescription
childrenComponentChildrenrequiredContent to render when authenticated
fallbackComponentChildrennullShown while loading or redirecting
autoRefreshbooleantrueAuto-refresh expired tokens before redirecting to login
loginOptionsLoginOptions-Options passed to actions.login() when redirecting

When RequireAuth renders:

  1. If still loading (discovery, callback), render fallback
  2. If authenticated with a valid token, render children
  3. If the token is expired and autoRefresh is true, attempt a silent refresh
  4. If refresh succeeds, render children with the new token
  5. If refresh fails (or no refresh token), redirect to the IdP login
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>
);
}