{"id":15740,"library":"oidc-client-ts","title":"OpenID Connect & OAuth2 Client (TypeScript)","description":"oidc-client-ts is an actively maintained TypeScript library, currently at version 3.5.0, providing OpenID Connect (OIDC) and OAuth2 protocol support for client-side, browser-based JavaScript applications. It includes robust features for user session and access token management. This project is a direct fork of the unmaintained `IdentityModel/oidc-client-js`, ported to TypeScript with a largely similar API for its 2.0 release. Moving forward, it prioritizes OAuth 2.1 protocols and explicitly *does not* support the deprecated implicit grant. A key change since v3.x is the transition from `crypto-js` to the browser's native `crypto.subtle` module for cryptographic operations, which mandates the use of secure contexts (HTTPS). The library supports various flows, including Authorization Code Grant with PKCE, Authorization Code Grant, Resource Owner Password Credentials (ROPC) Grant, Refresh Token Grant, and Silent Refresh Token in iframe Flow.","status":"active","version":"3.5.0","language":"javascript","source_language":"en","source_url":"https://github.com/authts/oidc-client-ts","tags":["javascript","authentication","oauth2","oidc","openid","OpenID Connect","typescript"],"install":[{"cmd":"npm install oidc-client-ts","lang":"bash","label":"npm"},{"cmd":"yarn add oidc-client-ts","lang":"bash","label":"yarn"},{"cmd":"pnpm add oidc-client-ts","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"UserManager is the primary class for high-level OIDC/OAuth2 operations. ESM import is standard; CommonJS `require` is a common mistake for modern browser/bundler environments.","wrong":"const UserManager = require('oidc-client-ts').UserManager;","symbol":"UserManager","correct":"import { UserManager } from 'oidc-client-ts';"},{"note":"Used for configuring the `userStore` option in UserManagerSettings, typically with `localStorage` or `sessionStorage`. Direct import from `src/` path is incorrect and not stable.","wrong":"import { WebStorageStateStore } from 'oidc-client-ts/src/WebStorageStateStore';","symbol":"WebStorageStateStore","correct":"import { WebStorageStateStore } from 'oidc-client-ts';"},{"note":"Provides logging utilities. You can configure a custom logger and set the logging level using `Log.setLogger()` and `Log.setLevel()`.","wrong":"const Log = require('oidc-client-ts').Log;","symbol":"Log","correct":"import { Log } from 'oidc-client-ts';"}],"quickstart":{"code":"import { UserManager, WebStorageStateStore, Log } from 'oidc-client-ts';\n\n// Configure logging for better debugging\nLog.setLevel(Log.INFO);\nLog.setLogger(console);\n\nconst userManagerSettings = {\n  authority: 'https://demo.identityserver.io',\n  client_id: 'interactive.public.js',\n  redirect_uri: 'http://localhost:5003/signin-callback.html',\n  post_logout_redirect_uri: 'http://localhost:5003/signout-callback.html',\n  response_type: 'code',\n  scope: 'openid profile api offline_access',\n  // Use PKCE for enhanced security with authorization code flow\n  client_secret: process.env.OIDC_CLIENT_SECRET ?? '', // Only required for confidential clients\n  userStore: new WebStorageStateStore({ store: window.localStorage }),\n  automaticSilentRenew: true,\n  // Ensure this matches the origin of your app, especially for silent renew iframes\n  monitorSession: true,\n  checkSessionIntervalInSeconds: 3,\n};\n\nconst userManager = new UserManager(userManagerSettings);\n\n// Handle the signin redirect callback in your callback page\nasync function handleSigninCallback() {\n  try {\n    const user = await userManager.signinRedirectCallback();\n    console.log('Signed in:', user);\n    // Redirect to your application's main page or show user info\n  } catch (error) {\n    console.error('Error handling signin callback:', error);\n  }\n}\n\n// Trigger signin (e.g., from a login button)\nasync function signIn() {\n  try {\n    await userManager.signinRedirect();\n  } catch (error) {\n    console.error('Error initiating signin:', error);\n  }\n}\n\n// Example usage (assuming a simple HTML page):\n// On your main page:\n// document.getElementById('loginButton').addEventListener('click', signIn);\n\n// On your signin-callback.html page:\n// window.onload = handleSigninCallback;\n\n// To simulate usage for demonstration:\nif (window.location.pathname === '/signin-callback.html') {\n  handleSigninCallback();\n} else {\n  console.log('User Manager initialized. Call signIn() to start login flow.');\n  // For demonstration, directly call signIn if not on callback page\n  // In a real app, this would be triggered by user action\n  // signIn();\n}\n\nexport { userManager, signIn, handleSigninCallback };","lang":"typescript","description":"This quickstart demonstrates how to initialize `UserManager`, configure basic OIDC settings, and handle the `signinRedirect` and `signinRedirectCallback` flow using a code example with TypeScript. It includes setting up logging and persistent user storage."},"warnings":[{"fix":"Ensure your application is served over HTTPS or use `localhost` for development. If supporting older browsers or insecure contexts is critical, consider staying on v2.x or implementing a polyfill (though `oidc-client-ts` itself does not officially support polyfilling for `crypto.subtle`).","message":"Since v3.0.0, `oidc-client-ts` no longer uses `crypto-js` and instead relies on the browser's native `crypto.subtle` module. This change mandates that your application must run in a 'secure context' (HTTPS). Using HTTP, even for local development (unless `localhost`), will result in errors.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Migrate from implicit grant to Authorization Code Grant with PKCE. Review the official migration guide from `oidc-client-js` to `oidc-client-ts` for detailed changes in settings and API usage.","message":"`oidc-client-ts` is a TypeScript port and successor to `IdentityModel/oidc-client-js`, which halted development in June 2021. While the API is largely similar to `oidc-client-js` v1.x, `oidc-client-ts` v2.0.0 removed support for the deprecated implicit grant flow, focusing exclusively on OAuth 2.1 compliant flows like the Authorization Code Grant with PKCE.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Carefully review the `UserManagerSettings` documentation and the migration guide for the specific version you are upgrading to, especially regarding time-related settings which often changed units or names.","message":"The `UserManagerSettings` object has several properties that were renamed or had their default values changed between `oidc-client-js` v1.x and `oidc-client-ts` v2.0.0, and again from v2.x to v3.x. For example, `clockSkew` became `clockSkewInSeconds`, `loadUserInfo` default changed from `true` to `false`, and `revokeAccessTokenOnSignout` became `revokeTokensOnSignout`.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Double-check that your `redirect_uri` (and `post_logout_redirect_uri`, `silent_redirect_uri`) configuration in `UserManagerSettings` exactly matches what's registered with your Identity Provider. Incorrect values are a common source of authentication failures. Ensure CORS headers are correctly configured on your OIDC/OAuth2 provider if you need to fetch metadata from a different origin.","message":"Proper configuration of `authority`, `client_id`, and `redirect_uri` is crucial. The `redirect_uri` must be precisely registered with your OIDC/OAuth2 provider and match the one used in the client application, including scheme (HTTP/HTTPS), hostname, and path.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Serve your application over HTTPS, even for development, or ensure you are developing on `localhost`.","cause":"Attempting to run `oidc-client-ts` v3.x or later in an insecure HTTP context (non-localhost). The library relies on `window.crypto.subtle`, which browsers restrict to HTTPS or localhost.","error":"Oops... Crypto. Subtle is available only in secure contexts (HTTPS)"},{"fix":"Verify that the `redirect_uri` in your `UserManager` configuration is identical to one registered with your Identity Provider, including scheme (http/https), hostname, and path. Check your browser's network tab for the exact redirect URL used.","cause":"The `redirect_uri` configured in `UserManagerSettings` does not exactly match a pre-registered redirect URI on your OIDC/OAuth2 Identity Provider, or the response from the IdP is redirecting to an unrecognized URI.","error":"Error: No matching redirect URI found"},{"fix":"Ensure `WebStorageStateStore` is correctly configured and accessible (e.g., using `localStorage` instead of `sessionStorage` if session persistence across tabs/windows is needed). Check for browser settings that might block storage access in iframes for silent renews. Review application navigation logic to prevent premature state loss.","cause":"This typically occurs when the OIDC flow initiated with PKCE cannot complete because the `code_verifier` (a cryptographically random string generated at the start of the flow) is lost or unavailable during the callback. This can happen due to incorrect state store configuration, browser issues (e.g., third-party cookie blocking for iframes), or rapid page navigations.","error":"PKCE code_verifier was not found"},{"fix":"Implement robust error handling around `signinRedirectCallback()` and `getUser()`. Inspect the browser's console and network requests for errors during the OIDC flow. Ensure all required scopes are requested and granted, and that the IdP is correctly issuing tokens. Check `Log.setLevel(Log.DEBUG)` for more verbose output from `oidc-client-ts`.","cause":"This often indicates that the `User` object returned from the `signinRedirectCallback()` or `getUser()` method is `null` or `undefined`, meaning the authentication flow did not successfully complete or no user session was found. This could be due to an error during the OIDC response processing, an invalid token, or the user being unauthenticated.","error":"Cannot read properties of undefined (reading 'access_token') after sign-in"}],"ecosystem":"npm"}