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.
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.
oidc-client was the original standard for browser-based OIDC.
// 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.
// 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.
// 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.
oidc-client-ts.// 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 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.
// oidc-client-ts: PKCE handled automatically
await userManager.signinRedirect();
// No client_secret in config
openid-client supports confidential client flows.
client_secret_basic or client_secret_post.// 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.
// react-oidc-context: Secure hook usage
const { isAuthenticated, signoutRedirect } = useAuth();
// PKCE and token handling abstracted away
oidc-client had legacy security models.
// oidc-client: Legacy security (Risky)
// No type safety to prevent misconfiguration
userManager.signinRedirect();
Managing the user session lifecycle is a core task. Each library exposes this differently.
oidc-client-ts gives manual control over the user manager.
// 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.// 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.
// openid-client: Token validation
const claims = await client.userinfo(tokenSet.access_token);
// Validate claims on server side
oidc-client used older event patterns.
// oidc-client: Legacy events
userManager.events.addUserLoaded((user) => {
console.log("User loaded", user);
});
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.
// react-oidc-context: Protected Route
function ProtectedRoute() {
const { isAuthenticated } = useAuth();
return isAuthenticated ? <Dashboard /> : <Login />;
}
oidc-client-ts requires manual React integration.
// 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.
// 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.
// oidc-client: Callback pattern
userManager.signinRedirectCallback().then(function (user) {
// Handle success
}).catch(function (err) {
// Handle error
});
| Feature | oidc-client-ts | react-oidc-context | openid-client | oidc-client |
|---|---|---|---|---|
| Environment | Browser (SPA) | Browser (React) | Node.js (Backend) | Browser (Legacy) |
| Language | TypeScript | TypeScript | TypeScript/JS | JavaScript |
| Client Type | Public (PKCE) | Public (PKCE) | Confidential (Secret) | Public (PKCE) |
| Integration | Manual / Custom | React Hooks | Server Middleware | Manual / Legacy |
| Status | β Active | β Active | β Active | β Deprecated |
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.
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.
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.
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.
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.
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.
The following features are currently in scope and implemented in this software:
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!
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.
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.
openid-client is distributed via npmjs.com, jsr.io, and github.com.
example ESM import1
import * as client from 'openid-client'
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 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(),
)
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.
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 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)
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):
| Version | Security Fixes π | Other Bug Fixes π | New Features β | Runtime and Module type |
|---|---|---|---|---|
| v6.x | Security Policy | β | β | Universal3 ESM1 |