openid-client vs react-oidc-context vs oidc-client vs oidc-client-ts
Implementing OpenID Connect Authentication in JavaScript Applications
openid-clientreact-oidc-contextoidc-clientoidc-client-tsSimilar Packages:

Implementing OpenID Connect Authentication in JavaScript Applications

oidc-client is the legacy JavaScript library for browser-based OIDC authentication, now deprecated in favor of oidc-client-ts. oidc-client-ts is the modern TypeScript rewrite that serves as the core standard for Single Page Applications (SPAs). openid-client is a specialized library designed for Node.js backends and confidential clients, not browsers. react-oidc-context is a React-specific wrapper that simplifies integrating oidc-client-ts using hooks and context providers.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
openid-client15,729,8432,432222 kB0a month agoMIT
react-oidc-context779,9761,034118 kB947 months agoMIT
oidc-client02,420-1166 years agoApache-2.0
oidc-client-ts01,9641.73 MB1607 months agoApache-2.0

OpenID Connect Libraries: Architecture, Security, and Framework Integration

Implementing authentication in modern web applications requires careful selection of tools that match your runtime environment and framework. The oidc-client ecosystem has evolved significantly, shifting from legacy JavaScript to modern TypeScript, while distinct libraries serve backend versus frontend needs. Let's compare how these four packages handle authentication flows, environment constraints, and framework integration.

πŸ—οΈ Core Architecture and Runtime Environment

oidc-client was the original standard for browser-based OIDC.

  • Written in vanilla JavaScript.
  • Runs exclusively in the browser (SPA).
  • Status: Deprecated and archived.
// oidc-client: Legacy setup (Do Not Use)
const userManager = new Oidc.UserManager({
  authority: "https://accounts.google.com",
  client_id: "your-client-id",
  redirect_uri: "http://localhost:3000/callback"
});

oidc-client-ts is the direct successor and rewrite.

  • Written in TypeScript for type safety.
  • Runs exclusively in the browser (SPA).
  • Status: Active maintenance and recommended standard.
// oidc-client-ts: Modern setup
import { UserManager } from "oidc-client-ts";

const userManager = new UserManager({
  authority: "https://accounts.google.com",
  client_id: "your-client-id",
  redirect_uri: "http://localhost:3000/callback"
});

openid-client targets server-side environments.

  • Designed for Node.js backends.
  • Supports confidential clients (client secrets).
  • Status: Active maintenance for backend use.
// openid-client: Backend setup
import { customFetch, Issuer } from "openid-client";

const issuer = await Issuer.discover("https://accounts.google.com");
const client = new issuer.Client({
  client_id: "your-client-id",
  client_secret: "your-client-secret" // Secure on server
});

react-oidc-context wraps the browser client for React.

  • Built on top of oidc-client-ts.
  • Provides React hooks and Context API.
  • Status: Active maintenance for React projects.
// react-oidc-context: React setup
import { AuthProvider } from "react-oidc-context";

const config = {
  authority: "https://accounts.google.com",
  client_id: "your-client-id",
  redirect_uri: "http://localhost:3000/callback"
};

// Wrap your app
<AuthProvider {...config}>...</AuthProvider>

πŸ” Security Model: Public vs Confidential Clients

Security boundaries define which library you can safely use. Browser-based apps are "public clients" and cannot store secrets. Server apps are "confidential clients" and should.

oidc-client-ts enforces public client security.

  • Uses PKCE (Proof Key for Code Exchange) by default.
  • No client secret is passed in the code.
  • Tokens stored in browser memory or storage.
// oidc-client-ts: PKCE handled automatically
await userManager.signinRedirect();
// No client_secret in config

openid-client supports confidential client flows.

  • Allows client_secret_basic or client_secret_post.
  • Suitable for backend-for-frontend (BFF) patterns.
  • Keeps tokens on the server, away from the browser.
// openid-client: Using client secret
const tokenSet = await client.callback(redirectUri, params, {
  code_verifier: "verifier",
  state: "state"
});
// Secret used internally during token exchange

react-oidc-context inherits oidc-client-ts security.

  • Same PKCE requirements.
  • Adds React-specific security like automatic session monitoring.
  • Keeps implementation consistent with the underlying library.
// react-oidc-context: Secure hook usage
const { isAuthenticated, signoutRedirect } = useAuth();
// PKCE and token handling abstracted away

oidc-client had legacy security models.

  • Lacked modern TypeScript safety checks.
  • No longer updated for new security threats.
  • Risk of vulnerabilities in token handling.
// oidc-client: Legacy security (Risky)
// No type safety to prevent misconfiguration
userManager.signinRedirect(); 

πŸ”„ Handling Authentication State and Tokens

Managing the user session lifecycle is a core task. Each library exposes this differently.

oidc-client-ts gives manual control over the user manager.

  • You explicitly call methods to get the user.
  • You must wire up event listeners for token expiration.
  • Best for non-framework or custom framework setups.
// oidc-client-ts: Manual user retrieval
const user = await userManager.getUser();
if (user?.access_token) {
  // Attach token to API calls
}

react-oidc-context automates state via hooks.

  • useAuth hook provides reactive user state.
  • Automatically triggers re-renders on login/logout.
  • Reduces boilerplate for React components.
// react-oidc-context: Reactive state
const { user, isLoading } = useAuth();

if (isLoading) return <div>Loading...</div>;
return <div>Hello {user?.profile.name}</div>;

openid-client manages sessions on the server.

  • You handle sessions via cookies or server memory.
  • No browser-based user object to manage directly.
  • Focuses on validating tokens received from the frontend.
// openid-client: Token validation
const claims = await client.userinfo(tokenSet.access_token);
// Validate claims on server side

oidc-client used older event patterns.

  • Relied on global callbacks.
  • Harder to integrate with modern component lifecycles.
  • Deprecated event handling mechanisms.
// oidc-client: Legacy events
userManager.events.addUserLoaded((user) => {
  console.log("User loaded", user);
});

🧩 Framework Integration and Boilerplate

The amount of code you write depends on how much the library abstracts for your specific framework.

react-oidc-context is purpose-built for React.

  • Minimal setup code for standard flows.
  • Integrated loading and error states.
  • Ideal for teams wanting speed in React ecosystems.
// react-oidc-context: Protected Route
function ProtectedRoute() {
  const { isAuthenticated } = useAuth();
  return isAuthenticated ? <Dashboard /> : <Login />;
}

oidc-client-ts requires manual React integration.

  • You must create your own Context or Hooks.
  • More flexible for Vue, Angular, or Svelte.
  • Better if you need full control over the lifecycle.
// oidc-client-ts: Custom React Hook
function useUserManager() {
  const [user, setUser] = useState(null);
  // Manual wiring of userManager events required
  return user;
}

openid-client integrates with Express or NestJS.

  • Used in route handlers or middleware.
  • No frontend component integration.
  • Essential for BFF (Backend for Frontend) architectures.
// openid-client: Express Middleware
app.get("/profile", async (req, res) => {
  const tokens = req.session.tokens;
  const userinfo = await client.userinfo(tokens.access_token);
  res.json(userinfo);
});

oidc-client requires legacy integration patterns.

  • Callback-based patterns instead of Promises.
  • More verbose error handling.
  • Not compatible with modern TypeScript projects.
// oidc-client: Callback pattern
userManager.signinRedirectCallback().then(function (user) {
  // Handle success
}).catch(function (err) {
  // Handle error
});

πŸ“Š Summary: Key Differences

Featureoidc-client-tsreact-oidc-contextopenid-clientoidc-client
EnvironmentBrowser (SPA)Browser (React)Node.js (Backend)Browser (Legacy)
LanguageTypeScriptTypeScriptTypeScript/JSJavaScript
Client TypePublic (PKCE)Public (PKCE)Confidential (Secret)Public (PKCE)
IntegrationManual / CustomReact HooksServer MiddlewareManual / Legacy
Statusβœ… Activeβœ… Activeβœ… Active❌ Deprecated

πŸ’‘ The Big Picture

oidc-client-ts is the foundation πŸ—οΈ for any browser-based authentication. Use it directly if you are not using React or need maximum control over the authentication lifecycle.

react-oidc-context is the accelerator πŸš€ for React teams. It removes the boilerplate of wiring up oidc-client-ts manually, letting you focus on building UI components rather than auth logic.

openid-client is the secure vault πŸ”’ for your backend. Use it when you need to keep tokens off the client entirely (BFF pattern) or when your backend needs to call other APIs on behalf of the user.

oidc-client is the legacy system πŸ•ΈοΈ. Do not start new projects with it. If you are still using it, treat migration to oidc-client-ts as a security priority.

Final Thought: Security and environment are your primary decision factors. If you are in the browser, use oidc-client-ts (or its React wrapper). If you are on the server, use openid-client. Never mix confidential client secrets into browser-based libraries.

How to Choose: openid-client vs react-oidc-context vs oidc-client vs oidc-client-ts

  • openid-client:

    Choose openid-client if you are implementing authentication on a Node.js backend or a confidential client where you can safely store a client secret. It is not suitable for browser-based SPAs due to security risks associated with exposing secrets in client-side code.

  • react-oidc-context:

    Choose react-oidc-context if you are building a React application and want a streamlined integration. It wraps oidc-client-ts to provide easy-to-use hooks like useAuth and context providers, reducing the boilerplate required to manage user sessions and authentication state.

  • oidc-client:

    Avoid this package for any new development. It is officially deprecated and no longer receives security updates or bug fixes. If you are maintaining a legacy system using this, plan a migration to oidc-client-ts immediately to ensure security compliance.

  • oidc-client-ts:

    Choose oidc-client-ts if you are building a vanilla JavaScript or TypeScript Single Page Application (SPA) without a specific framework wrapper. It provides the core OIDC protocol implementation, token management, and silent renew features for public clients running in the browser.

README for openid-client

openid-client

OAuth 2 / OpenID Connect Client API for JavaScript Runtimes

openid-client simplifies integration with authorization servers by providing easy-to-use APIs for the most common authentication and authorization flows, including OAuth 2 and OpenID Connect. It is designed for JavaScript runtimes like Node.js, Browsers, Deno, Cloudflare Workers, and more.

Features

The following features are currently in scope and implemented in this software:

  • Authorization Server Metadata discovery
  • Authorization Code Flow (profiled under OpenID Connect 1.0, OAuth 2.0, OAuth 2.1, FAPI 1.0 Advanced, and FAPI 2.0)
  • Refresh Token, Device Authorization, Client-Initiated Backchannel Authentication (CIBA), and Client Credentials Grants
  • Demonstrating Proof-of-Possession at the Application Layer (DPoP)
  • Token Introspection and Revocation
  • Pushed Authorization Requests (PAR)
  • UserInfo and Protected Resource Requests
  • Authorization Server Issuer Identification
  • JWT Secured Introspection, Response Mode (JARM), Authorization Request (JAR), and UserInfo
  • Dynamic Client Registration (DCR)
  • Passport Strategy

Sponsor

Auth0 by Okta

If you want to quickly add authentication to JavaScript apps, feel free to check out Auth0's JavaScript SDK and free plan. Create an Auth0 account; it's free!

Certification

OpenID Certification

Filip Skokan has certified that this software conforms to the Basic, FAPI 1.0, and FAPI 2.0 Relying Party Conformance Profiles of the OpenID Connectβ„’ protocol.

πŸ’— Help the project

Support from the community to continue maintaining and improving this module is welcome. If you find the module useful, please consider supporting the project by becoming a sponsor.

API Reference Documentation

openid-client is distributed via npmjs.com, jsr.io, and github.com.

Examples

example ESM import1

import * as client from 'openid-client'
  • Authorization Code Flow (OAuth 2.0) - source
  • Authorization Code Flow (OpenID Connect) - source | diff
  • Extensions
  • Passport Strategy - source

Quick start

let server!: URL // Authorization Server's Issuer Identifier
let clientId!: string // Client identifier at the Authorization Server
let clientSecret!: string // Client Secret

let config: client.Configuration = await client.discovery(
  server,
  clientId,
  clientSecret,
)

Authorization Code Flow

Authorization Code flow is for obtaining Access Tokens (and optionally Refresh Tokens) to use with third party APIs.

When you want to have your end-users authorize or authenticate you need to send them to the authorization server's authorization_endpoint. Consult the web framework of your choice on how to redirect but here's how to get the authorization endpoint's URL with parameters already encoded in the query to redirect to.

/**
 * Value used in the authorization request as the redirect_uri parameter, this
 * is typically pre-registered at the Authorization Server.
 */
let redirect_uri!: string
let scope!: string // Scope of the access request
/**
 * PKCE: The following MUST be generated for every redirect to the
 * authorization_endpoint. You must store the code_verifier and state in the
 * end-user session such that it can be recovered as the user gets redirected
 * from the authorization server back to your application.
 */
let code_verifier: string = client.randomPKCECodeVerifier()
let code_challenge: string =
  await client.calculatePKCECodeChallenge(code_verifier)
let state!: string

let parameters: Record<string, string> = {
  redirect_uri,
  scope,
  code_challenge,
  code_challenge_method: 'S256',
}

if (!config.serverMetadata().supportsPKCE()) {
  /**
   * We cannot be sure the server supports PKCE so we're going to use state too.
   * Use of PKCE is backwards compatible even if the AS doesn't support it which
   * is why we're using it regardless. Like PKCE, random state must be generated
   * for every redirect to the authorization_endpoint.
   */
  state = client.randomState()
  parameters.state = state
}

let redirectTo: URL = client.buildAuthorizationUrl(config, parameters)

// now redirect the user to redirectTo.href
console.log('redirecting to', redirectTo.href)

When end-users are redirected back to the redirect_uri your application consumes the callback and passes in PKCE code_verifier to include it in the authorization code grant token exchange.

let getCurrentUrl!: (...args: any) => URL

let tokens: client.TokenEndpointResponse = await client.authorizationCodeGrant(
  config,
  getCurrentUrl(),
  {
    pkceCodeVerifier: code_verifier,
    expectedState: state,
  },
)

console.log('Token Endpoint Response', tokens)

You can then fetch a protected resource response

let protectedResourceResponse: Response = await client.fetchProtectedResource(
  config,
  tokens.access_token,
  new URL('https://rs.example.com/api'),
  'GET',
)

console.log(
  'Protected Resource Response',
  await protectedResourceResponse.json(),
)

Device Authorization Grant (Device Flow)

let scope!: string // Scope of the access request

let response = await client.initiateDeviceAuthorization(config, { scope })

console.log('User Code:', response.user_code)
console.log('Verification URI:', response.verification_uri)
console.log('Verification URI (complete):', response.verification_uri_complete)

You will display the instructions to the end-user and have them directed at verification_uri or verification_uri_complete, afterwards you can start polling for the Device Access Token Response.

let tokens: client.TokenEndpointResponse =
  await client.pollDeviceAuthorizationGrant(config, response)

console.log('Token Endpoint Response', tokens)

This will poll in a regular interval and only resolve with tokens once the end-user authenticates.

Client-Initiated Backchannel Authentication (CIBA)

let scope!: string // Scope of the access request
/**
 * One of login_hint, id_token_hint, or login_hint_token parameters must be
 * provided in CIBA
 */
let login_hint!: string

let response = await client.initiateBackchannelAuthentication(config, {
  scope,
  login_hint,
})

/**
 * OPTIONAL: If your client is configured with Ping Mode you'd invoke the
 * following after getting the CIBA Ping Callback (its implementation is
 * framework specific and therefore out of scope for openid-client)
 */

let tokens: client.TokenEndpointResponse =
  await client.pollBackchannelAuthenticationGrant(config, response)

console.log('Token Endpoint Response', tokens)

This will poll in a regular interval and only resolve with tokens once the end-user authenticates.

Client Credentials Grant

Client Credentials flow is for obtaining Access Tokens to use with third party APIs on behalf of your application, rather than an end-user which was the case in previous examples.

let scope!: string // Scope of the access request
let resource!: string // Resource Indicator of the Resource Server the access token is for

let tokens: client.TokenEndpointResponse = await lib.clientCredentialsGrant(
  config,
  { scope, resource },
)

console.log('Token Endpoint Response', tokens)

Supported Runtimes

The supported JavaScript runtimes include those that support the utilized Web API globals and standard built-in objects. These are (but are not limited to):

  • Browsers
  • Bun
  • Cloudflare Workers
  • Deno
  • Electron
  • Node.js2

Supported Versions

VersionSecurity Fixes πŸ”‘Other Bug Fixes 🐞New Features ⭐Runtime and Module type
v6.xSecurity Policyβœ…βœ…Universal3 ESM1

Footnotes

  1. CJS style let client = require('openid-client') is possible in Node.js versions where the require(esm) feature is enabled by default (^20.19.0 || ^22.12.0 || >= 23.0.0). ↩ ↩2

  2. Node.js v20.x as baseline is required ↩

  3. Assumes runtime support of WebCryptoAPI and Fetch API ↩