Skip to content

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 Preact context.

Terminal window
npm install oidc-js-preact
import { AuthProvider } from "oidc-js-preact";
const config = {
issuer: "https://auth.example.com",
clientId: "my-app",
redirectUri: "http://localhost:3000/callback",
scopes: ["openid", "profile", "email", "offline_access"],
postLogoutRedirectUri: "http://localhost:3000",
};
function App() {
return (
<AuthProvider config={config}>
<MyApp />
</AuthProvider>
);
}
PropTypeDefaultDescription
configOidcConfigrequiredOIDC configuration (issuer, clientId, redirectUri, etc.)
fetchProfilebooleantrueWhether 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
childrenComponentChildrenrequiredChild components

By default, AuthProvider restores the pre-login URL using window.history.replaceState. If you use a client-side router, handle navigation yourself:

import { AuthProvider } from "oidc-js-preact";
import { route } from "preact-router";
function App() {
return (
<AuthProvider
config={config}
onLogin={(returnTo) => route(returnTo)}
>
<MyApp />
</AuthProvider>
);
}
  1. On mount, AuthProvider creates an OidcClient and calls client.init()
  2. init() fetches the OIDC discovery document
  3. If the URL contains a code and state parameter (callback from IdP), it exchanges the code for tokens
  4. If the URL contains an error parameter, it calls onError
  5. On unmount, it unsubscribes and destroys the client