Skip to content

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).

  1. Install the package

    Terminal window
    npm install oidc-js-react
  2. 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)
  3. Wrap your app with AuthProvider

    // main.tsx
    import { 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>
    );
  4. Use the useAuth hook

    // App.tsx
    import { 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>
    );
    }
  5. Protect routes

    import { RequireAuth } from "oidc-js-react";
    function ProtectedPage() {
    return (
    <RequireAuth>
    <p>This content is only visible to authenticated users.</p>
    </RequireAuth>
    );
    }
  1. AuthProvider fetches the OIDC discovery document from {issuer}/.well-known/openid-configuration
  2. When actions.login() is called, it generates PKCE parameters, saves auth state to sessionStorage, and redirects to the IdP’s authorization endpoint
  3. After the user authenticates, the IdP redirects back with an authorization code
  4. AuthProvider detects the code in the URL, exchanges it for tokens, fetches the user profile, and cleans up the URL
  5. RequireAuth checks token expiry on each render and automatically refreshes expired tokens using the refresh token