Quickstart
This guide walks through adding OIDC authentication to a React app. You’ll need an OIDC provider (like Autentico, Auth0, Keycloak, or any spec-compliant IdP).
-
Install the package
Terminal window npm install oidc-js-react -
Configure the provider
You’ll need these values from your IdP:
- Issuer URL — the base URL of your OIDC provider (e.g.
https://auth.example.com) - Client ID — registered in your IdP’s client/application settings
- Redirect URI — where the IdP sends the user after login (must be registered)
- Issuer URL — the base URL of your OIDC provider (e.g.
-
Wrap your app with AuthProvider
// main.tsximport { StrictMode } from "react";import { createRoot } from "react-dom/client";import { AuthProvider } from "oidc-js-react";import App from "./App";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",};createRoot(document.getElementById("root")!).render(<StrictMode><AuthProvider config={config}><App /></AuthProvider></StrictMode>); -
Use the
useAuthhook// App.tsximport { useAuth } from "oidc-js-react";function App() {const { isAuthenticated, isLoading, user, actions } = useAuth();if (isLoading) return <div>Loading...</div>;if (!isAuthenticated) {return <button onClick={() => actions.login()}>Log in</button>;}return (<div><p>Welcome, {user?.profile?.name ?? user?.claims.sub}!</p><button onClick={() => actions.logout()}>Log out</button></div>);} -
Protect routes
import { RequireAuth } from "oidc-js-react";function ProtectedPage() {return (<RequireAuth><p>This content is only visible to authenticated users.</p></RequireAuth>);}
What happens under the hood
Section titled “What happens under the hood”AuthProviderfetches the OIDC discovery document from{issuer}/.well-known/openid-configuration- When
actions.login()is called, it generates PKCE parameters, saves auth state tosessionStorage, and redirects to the IdP’s authorization endpoint - After the user authenticates, the IdP redirects back with an authorization code
AuthProviderdetects the code in the URL, exchanges it for tokens, fetches the user profile, and cleans up the URLRequireAuthchecks token expiry on each render and automatically refreshes expired tokens using the refresh token