AuthProvider
AuthProvider is the top-level component that manages OIDC state. It creates an OidcClient instance, handles the authorization callback, and provides authentication state to all child components via React context.
import { AuthProvider } from "oidc-js-react";
const config = { issuer: "https://auth.example.com", clientId: "my-app", redirectUri: "http://localhost:5173/callback", scopes: ["openid", "profile", "email", "offline_access"], postLogoutRedirectUri: "http://localhost:5173",};
function App() { return ( <AuthProvider config={config}> <MyApp /> </AuthProvider> );}| Prop | Type | Default | Description |
|---|---|---|---|
config | OidcConfig | required | OIDC configuration (issuer, clientId, redirectUri, etc.) |
fetchProfile | boolean | true | Whether to fetch the UserInfo endpoint after login |
onLogin | (returnTo: string) => void | — | Called after successful login with the URL to restore |
onError | (error: Error) => void | — | Called when an error occurs during initialization |
children | ReactNode | required | Child components |
Config
Section titled “Config”interface OidcConfig { issuer: string; // IdP base URL (e.g. "https://auth.example.com") clientId: string; // Registered client ID clientSecret?: string; // For confidential clients (not used in SPAs) redirectUri?: string; // Callback URL after login scopes?: string[]; // Requested scopes (default: ["openid"]) postLogoutRedirectUri?: string; // Where to go after logout}onLogin callback
Section titled “onLogin callback”By default, AuthProvider restores the pre-login URL using window.history.replaceState. If you’re using a client-side router, you may want to handle navigation yourself:
import { useNavigate } from "react-router-dom";
function App() { const navigate = useNavigate();
return ( <AuthProvider config={config} onLogin={(returnTo) => navigate(returnTo)} > <MyApp /> </AuthProvider> );}Lifecycle
Section titled “Lifecycle”- On mount,
AuthProvidercreates anOidcClientand callsclient.init() init()fetches the OIDC discovery document- If the URL contains a
codeandstateparameter (callback from IdP), it exchanges the code for tokens - If the URL contains an
errorparameter, it sets the error state - On unmount, it calls
client.destroy()to abort in-flight requests