# JavaScript OAuth clients libraries

JavaScript OAuth libraries run the OAuth and OpenID Connect flows that let an app act for a user at another service. A client sends the user to the provider's authorization page and exchanges the returned code for tokens. These libraries let apps offer sign-in with an identity provider and let agents call APIs with a user's delegated permission.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [oauth4webapi](#oauth-webapi) | 97.0M | 806 | Sep 2026 | MIT |
| [openid-client](#openid-client) | 91.2M | 2.5K | Nov 2026 | MIT |
| [oauth](#oauth) | 32.6M | 2.4K | Mar 2025 | MIT |
| [oidc-client-ts](#oidc-client-ts) | 12.0M | 2.0K | Mar 2026 | Apache-2.0 |
| [passport-oauth2](#passport-oauthtwo) | 11.8M | 617 | Feb 2024 | MIT |
| [arctic](#arctic) | 5.9M | 1.7K | May 2025 | MIT |
| [react-oidc-context](#react-oidc-context) | 4.2M | 1.0K | Mar 2026 | MIT |
| [simple-oauth2](#simple-oauth) | 3.3M | 1.6K | Jun 2024 | Apache-2.0 |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[oauth4webapi](#oauth-webapi) has the most monthly downloads in this comparison, at 94.0M.

## Capabilities

| Library | Metadata discovery | PKCE generation |
| --- | --- | --- |
| [oauth4webapi](#oauth-webapi) | Yes | Yes |
| [openid-client](#openid-client) | Yes | Yes |
| [oauth](#oauth) | No | No |
| [oidc-client-ts](#oidc-client-ts) | Yes | Yes |
| [passport-oauth2](#passport-oauthtwo) | No | Yes |
| [arctic](#arctic) | No | Yes |
| [react-oidc-context](#react-oidc-context) | Yes | Yes |
| [simple-oauth2](#simple-oauth) | No | No |

## Libraries

### oauth4webapi

[GitHub](https://github.com/panva/oauth4webapi) · [npm](https://www.npmjs.com/package/oauth4webapi) · [Docs](https://api.github.com/repos/panva/oauth4webapi/readme)

Provides low-level OAuth and OpenID Connect request and response routines.

- Downloads / mo: 97.0M
- Stars: 806
- Last release: 3.8.8
- License: MIT
- Capabilities: [From the oauth4webapi docs](https://api.github.com/repos/panva/oauth4webapi/readme)

**Strengths**

- **Exposes individual protocol steps.** Build custom clients from separate request and response routines.
- **Includes token inspection and revocation.** Inspect token status or request revocation through native protocol routines.

**Watch out for**

- **Responses need explicit processing.** Pass the grant response to processAuthorizationCodeResponse before consuming its result.
- **Uses ES modules.** CommonJS loading depends on runtime support for requiring ES modules.

```sh
npm install oauth4webapi@3.8.8
```

**akuity/kargo** (3.8K stars)

[akuity/kargo](https://github.com/akuity/kargo) 

```javascript
const login = async () => {
    if (!as?.authorization_endpoint) {
      return;
    }

    const code_verifier = generateRandomCodeVerifier();
    sessionStorage.setItem(codeVerifierKey, code_verifier);
    const state = generateRandomState();
    sessionStorage.setItem(stateKey, state);
    sessionStorage.setItem(platformRedirectKey, window.location.search);

    const code_challenge = await calculatePKCECodeChallenge(code_verifier);
    const url = new URL(as.authorization_endpoint);
    url.searchParams.set('client_id', client.client_id);
    url.searchParams.set('code_challenge', code_challenge);
    url.searchParams.set('code_challenge_method', 'S256');
    url.searchParams.set('redirect_uri', redirectURI);
    url.searchParams.set('response_type', 'code');
    url.searchParams.set('scope', getOIDCScopes(oidcConfig, as).join(' '));
    url.searchParams.set('state', state);

    window.location.replace(url.toString());
  };

```

[ui/src/features/auth/oidc-login.tsx](https://github.com/akuity/kargo/blob/a307deca88fd3efe39a0be89e3c45e82fe5f862f/ui/src/features/auth/oidc-login.tsx) · [More projects using oauth4webapi →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20oauth4webapi%20for%20OAuth%20client%20flows&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import * as oauth from "oauth4webapi";
const issuer = new URL(process.env.OAUTH_ISSUER);
const response = await oauth.discoveryRequest(issuer);
const metadata = await oauth.processDiscoveryResponse(issuer, response);
console.log(metadata.authorization_endpoint);

```

From [client_credentials.ts](https://api.github.com/repos/panva/oauth4webapi/contents/src/index.ts)

### openid-client

[GitHub](https://github.com/panva/openid-client) · [npm](https://www.npmjs.com/package/openid-client) · [Docs](https://api.github.com/repos/panva/openid-client/readme)

Provides OAuth and OpenID Connect client flows across JavaScript runtimes.

- Downloads / mo: 91.2M
- Stars: 2.5K
- Last release: 6.9.0
- License: MIT
- Capabilities: [From the openid-client docs](https://api.github.com/repos/panva/openid-client/readme)

**Strengths**

- **Discovers authorization server settings.** Use discovery to load server metadata and configure the client.
- **Includes device authorization.** Display the verification instructions, then poll for tokens after user approval.

**Watch out for**

- **Redirect state needs session storage.** Retain the verifier and state until the user returns.
- **Requires Web Crypto and Fetch.** Choose a runtime that supplies both Web APIs.

```sh
npm install openid-client@6.9.0
```

**immich-app/immich** (112.9K stars)

[immich-app/immich](https://github.com/immich-app/immich) 

```javascript
async authorize(config: OAuthConfig, redirectUrl: string, state?: string, codeChallenge?: string) {
    const client = await this.getClient(config);
    state ??= randomState();

    let codeVerifier: string | null;
    if (codeChallenge) {
      codeVerifier = null;
    } else {
      codeVerifier = randomPKCECodeVerifier();
      codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
    }

    const params: Record<string, string> = {
      redirect_uri: redirectUrl,
      scope: config.scope,
      state,
    };

    if (config.prompt) {
      params.prompt = config.prompt;
    }

    if (client.serverMetadata().supportsPKCE()) {
      params.code_challenge = codeChallenge;
      params.code_challenge_method = 'S256';
    }

    const url = buildAuthorizationUrl(client, params).href;

    return { url, state, codeVerifier };
  }

```

[server/src/repositories/oauth.repository.ts](https://github.com/immich-app/immich/blob/ff445d5fda8bf396e769df8977c316726dc25c9c/server/src/repositories/oauth.repository.ts) · [More projects using openid-client →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20openid-client%20for%20OAuth%20client%20flows&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import * as client from "openid-client";
const config = await client.discovery(new URL(process.env.OAUTH_ISSUER), process.env.OAUTH_CLIENT_ID);
console.log(config.serverMetadata().issuer);

```

From [oauth.ts](https://api.github.com/repos/panva/openid-client/readme)

### oauth

[GitHub](https://github.com/ciaranj/node-oauth) · [npm](https://www.npmjs.com/package/oauth) · [Docs](https://api.github.com/repos/ciaranj/node-oauth/readme)

Interacts with OAuth 1.0, 1.0A, 2, and Echo providers.

- Downloads / mo: 32.6M
- Stars: 2.4K
- Last release: 0.10.2
- License: MIT
- Capabilities: [From the oauth docs](https://api.github.com/repos/ciaranj/node-oauth/readme)

```sh
npm install oauth@0.10.2
```

**gitpod-io/gitpod** (13.8K stars)

[gitpod-io/gitpod](https://github.com/gitpod-io/gitpod) 

```javascript
protected patch_getOAuthAccessToken() {
    const oauth2 = this._oauth2;
    const _oauth2_getOAuthAccessToken = oauth2.getOAuthAccessToken as (
        code: string,
        params: any,
        callback: oauth2tokenCallback,
    ) => void;
    (oauth2 as any).getOAuthAccessToken = (code: string, params: any, callback: oauth2tokenCallback) => {
        const patchedCallback: oauth2tokenCallback = (err, accessToken, refreshToken, params) => {
            if (err) {
                return callback(err, null as any, null as any, null as any);
            }
            if (!accessToken) {
                return callback(
                    {
                        statusCode: 400,
                        data: JSON.stringify(params),
                    },
                    null as any,
                    null as any,
                    null as any,
                );
            }
            callback(null as any, accessToken, refreshToken, params);
        };
        _oauth2_getOAuthAccessToken.call(oauth2, code, params, patchedCallback);
    };
}

```

[components/server/src/auth/generic-auth-provider.ts](https://github.com/gitpod-io/gitpod/blob/beb925e048afccd5ebaddf367dec18b48d661790/components/server/src/auth/generic-auth-provider.ts) · [More projects using oauth →](https://dashboard.exa.ai/playground/search?q=oauth%20GitHub%20projects)

**Quickstart**

```javascript
const { OAuth2 } = require("oauth");
const client = new OAuth2(process.env.OAUTH_CLIENT_ID, null, process.env.OAUTH_BASE_URL, "/authorize", "/token");
const state = require("node:crypto").randomBytes(32).toString("hex");
console.log(client.getAuthorizeUrl({ redirect_uri: process.env.OAUTH_REDIRECT_URI, response_type: "code", state }));

```

From [README.md](https://api.github.com/repos/ciaranj/node-oauth/contents/lib/oauth2.js)

### oidc-client-ts

[GitHub](https://github.com/authts/oidc-client-ts) · [npm](https://www.npmjs.com/package/oidc-client-ts) · [Docs](https://api.github.com/repos/authts/oidc-client-ts/readme)

Provides an OpenID Connect and OAuth2 client library.

- Downloads / mo: 12.0M
- Stars: 2.0K
- Last release: 3.5.0
- License: Apache-2.0
- Capabilities: [From the oidc-client-ts docs](https://api.github.com/repos/authts/oidc-client-ts/readme)

```sh
npm install oidc-client-ts@3.5.0
```

**authts/react-oidc-context** (1.0K stars)

[authts/react-oidc-context](https://github.com/authts/react-oidc-context) 

```javascript
export const AuthProvider = (props: AuthProviderProps): React.JSX.Element => {
    const {
        children,

        onSigninCallback,
        skipSigninCallback,

        matchSignoutCallback,
        onSignoutCallback,

        onRemoveUser,

        userManager: userManagerProp = null,
        ...userManagerSettings
    } = props;

    const [userManager] = React.useState(() => {
        return userManagerProp ??
            (UserManagerImpl
                ? new UserManagerImpl(userManagerSettings as UserManagerSettings)
                : ({ settings: userManagerSettings } as UserManager));
    });

    const [state, dispatch] = React.useReducer(reducer, initialAuthState);
    const userManagerContext = React.useMemo(
        () =>
            Object.assign(
                {
                    settings: userManager.settings,
                    events: userManager.events,
                },
                Object.fromEntries(
                    userManagerContextKeys.map((key) => [
                        key,
                        userManager[key]?.bind(userManager) ??
                        unsupportedEnvironment(key),
                    ]),
                ) as Pick<UserManager, typeof userManagerContextKeys[number]>,
                Object.fromEntries(
                    navigatorKeys.map((key) => [
                        key,
                        userManager[key]
                            ? async (args: ProcessResourceOwnerPasswordCredentialsArgs & never[]) => {
                                dispatch({
                                    type: "NAVIGATOR_INIT",
                                    method: key,
                                });
                                try {
                                    return await userManager[key](args);
                                } catch (error) {
                                    dispatch({
                                        type: "ERROR",
                                        error: {
                                            ...normalizeError(error, `Unknown error while executing ${key}(...).`),
                                            source: key,
                                            args: args,
                                        } as ErrorContext,
                                    });
                                    return null;
                                } finally {
                                    dispatch({ type: "NAVIGATOR_CLOSE" });
                                }
                            }
                            : unsupportedEnvironment(key),
                    ]),
                ) as Pick<UserManager, typeof navigatorKeys[number]>,
            ),
        [userManager],
    );
    const didInitialize = React.useRef(false);

    React.useEffect(() => {
        if (!userManager || didInitialize.current) {
            return;
        }
        didInitialize.current = true;

        void (async (): Promise<void> => {
            // sign-in
            try {
                let user: User | undefined | null = null;

                // check if returning back from authority server
                if (hasAuthParams() && !skipSigninCallback) {
                    user = await userManager.signinCallback();
                    if (onSigninCallback) await onSigninCallback(user);
                }
                user = !user ? await userManager.getUser() : user;
                dispatch({ type: "INITIALISED", user });
            } catch (error) {
                dispatch({
                    type: "ERROR",
                    error: signinError(error),
                });
            }

            // sign-out
            try {
                if (matchSignoutCallback && matchSignoutCallback(userManager.settings)) {
                    const resp = await userManager.signoutCallback();
                    if (onSignoutCallback) await onSignoutCallback(resp);
                }
            } catch (error) {
                dispatch({
                    type: "ERROR",
                    error: signoutError(error),
                });
            }
        })();
    }, [userManager, skipSigninCallback, onSigninCallback, onSignoutCallback, matchSignoutCallback]);

    // register to userManager events
    React.useEffect(() => {
        if (!userManager) return undefined;
        // event UserLoaded (e.g. initial load, silent renew success)
        const handleUserLoaded = (user: User) => {
            dispatch({ type: "USER_LOADED", user });
        };
        userManager.events.addUserLoaded(handleUserLoaded);

        // event UserUnloaded (e.g. userManager.removeUser)
        const handleUserUnloaded = () => {
            dispatch({ type: "USER_UNLOADED" });
        };
        userManager.events.addUserUnloaded(handleUserUnloaded);

        // event UserSignedOut (e.g. user was signed out in background (checkSessionIFrame option))
        const handleUserSignedOut = () => {
            dispatch({ type: "USER_SIGNED_OUT" });
        };
        userManager.events.addUserSignedOut(handleUserSignedOut);

        // event SilentRenewError (silent renew error)
        const handleSilentRenewError = (error: Error) => {
            dispatch({
                type: "ERROR",
                error: renewSilentError(error),
            });
        };
        userManager.events.addSilentRenewError(handleSilentRenewError);

        return () => {
            userManager.events.removeUserLoaded(handleUserLoaded);
            userManager.events.removeUserUnloaded(handleUserUnloaded);
            userManager.events.removeUserSignedOut(handleUserSignedOut);
            userManager.events.removeSilentRenewError(handleSilentRenewError);
        };
    }, [userManager]);

    const removeUser = React.useCallback(async () => {
        if (!userManager) unsupportedEnvironment("removeUser");
        await userManager.removeUser();
        if (onRemoveUser) await onRemoveUser();
    }, [userManager, onRemoveUser]);

    const contextValue = React.useMemo(() => {
        return {
            ...state,
            ...userManagerContext,
            removeUser,
        };
    }, [state, userManagerContext, removeUser]);

    return (
        <AuthContext.Provider value={contextValue}>
            {children}
        </AuthContext.Provider>
    );
};

```

[src/AuthProvider.tsx](https://github.com/authts/react-oidc-context/blob/80e60ae0b538afdb6e0be7016ec3430104b1bf42/src/AuthProvider.tsx) · [More projects using oidc-client-ts →](https://dashboard.exa.ai/playground/search?q=oidc-client-ts%20GitHub%20projects)

**Quickstart**

```javascript
import { UserManager } from "oidc-client-ts";
const manager = new UserManager({ authority: "https://issuer.example.com", client_id: "registered-client", redirect_uri: window.location.origin + "/callback", response_type: "code", scope: "openid profile" });
await manager.signinRedirect();

```

From [README.md](https://authts.github.io/oidc-client-ts/classes/UserManager.html)

### passport-oauth2

[GitHub](https://github.com/jaredhanson/passport-oauth2) · [npm](https://www.npmjs.com/package/passport-oauth2) · [Docs](https://api.github.com/repos/jaredhanson/passport-oauth2/readme)

Adds an OAuth 2.0 authentication strategy to Passport.

- Downloads / mo: 11.8M
- Stars: 617
- Last release: 1.8.0
- License: MIT
- Capabilities: [From the passport-oauth2 docs](https://api.github.com/repos/jaredhanson/passport-oauth2/readme)

```sh
npm install passport-oauth2@1.8.0
```

**jaredhanson/passport-google-oauth2** (832 stars)

[jaredhanson/passport-google-oauth2](https://github.com/jaredhanson/passport-google-oauth2) 

```javascript
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://accounts.google.com/o/oauth2/v2/auth';
  options.tokenURL = options.tokenURL || 'https://www.googleapis.com/oauth2/v4/token';

  OAuth2Strategy.call(this, options, verify);
  this.name = 'google';
  this._userProfileURL = options.userProfileURL || 'https://www.googleapis.com/oauth2/v3/userinfo';
  
  var url = uri.parse(this._userProfileURL);
  if (url.pathname.indexOf('/userinfo') == (url.pathname.length - '/userinfo'.length)) {
    this._userProfileFormat = 'openid';
  } else {
    this._userProfileFormat = 'google+'; // Google Sign-In
  }
}

```

[lib/strategy.js](https://github.com/jaredhanson/passport-google-oauth2/blob/79f9ed6878f1d11150243a1429acb7ba3211e239/lib/strategy.js) · [More projects using passport-oauth2 →](https://dashboard.exa.ai/playground/search?q=passport-oauth2%20GitHub%20projects)

**Quickstart**

```javascript
const { Strategy } = require("passport-oauth2");
const strategy = new Strategy({ authorizationURL: process.env.OAUTH_AUTHORIZATION_URL, tokenURL: process.env.OAUTH_TOKEN_URL, clientID: process.env.OAUTH_CLIENT_ID, clientSecret: process.env.OAUTH_CLIENT_SECRET, callbackURL: process.env.OAUTH_REDIRECT_URI, state: true }, (_accessToken, _refreshToken, _profile, done) => done(null, false));
console.log(strategy.name);

```

From [strategy.js](https://api.github.com/repos/jaredhanson/passport-oauth2/contents/lib/strategy.js)

### arctic

[GitHub](https://github.com/pilcrowonpaper/arctic) · [npm](https://www.npmjs.com/package/arctic) · [Docs](https://api.github.com/repos/pilcrowonpaper/arctic/readme)

Provides OAuth 2.0 clients for specific providers.

- Downloads / mo: 5.9M
- Stars: 1.7K
- Last release: 3.7.0
- License: MIT
- Capabilities: [From the arctic docs](https://api.github.com/repos/pilcrowonpaper/arctic/readme)

```sh
npm install arctic@3.7.0
```

**documenso/documenso** (15.8K stars)

[documenso/documenso](https://github.com/documenso/documenso) 

```javascript
export const handleOAuthAuthorizeUrl = async (options: HandleOAuthAuthorizeUrlOptions) => {
  const { c, clientOptions, redirectPath } = options;

  let prompt = options.prompt ?? 'login';

  if (!clientOptions.clientId || !clientOptions.clientSecret) {
    throw new AppError(AppErrorCode.NOT_SETUP);
  }

  const { authorization_endpoint } = await getOpenIdConfiguration(clientOptions.wellKnownUrl, {
    requiredScopes: clientOptions.scope,
  });

  const oAuthClient = new OAuth2Client(clientOptions.clientId, clientOptions.clientSecret, clientOptions.redirectUrl);

  const scopes = clientOptions.scope;
  const state = options.state ?? generateState();

  const codeVerifier = generateCodeVerifier();

  const url = oAuthClient.createAuthorizationURLWithPKCE(
    authorization_endpoint,
    state,
    CodeChallengeMethod.S256,
    codeVerifier,
    scopes,
  );

  // Pass the prompt to the authorization endpoint.
  if (process.env.NEXT_PRIVATE_OIDC_PROMPT && isOidcPrompt(process.env.NEXT_PRIVATE_OIDC_PROMPT)) {
    prompt = process.env.NEXT_PRIVATE_OIDC_PROMPT;
  }

  url.searchParams.set('prompt', prompt);

  setCookie(c, `${clientOptions.id}_oauth_state`, state, {
    ...sessionCookieOptions,
    sameSite: 'lax',
    maxAge: oauthCookieMaxAge,
  });

  setCookie(c, `${clientOptions.id}_code_verifier`, codeVerifier, {
    ...sessionCookieOptions,
    sameSite: 'lax',
    maxAge: oauthCookieMaxAge,
  });

  if (redirectPath) {
    setCookie(c, `${clientOptions.id}_redirect_path`, `${state} ${redirectPath}`, {
      ...sessionCookieOptions,
      sameSite: 'lax',
      maxAge: oauthCookieMaxAge,
    });
  }

  return c.json({
    redirectUrl: url.toString(),
  });
};

```

[packages/auth/server/lib/utils/handle-oauth-authorize-url.ts](https://github.com/documenso/documenso/blob/125ff95097fb10704520cf03ec511a3df188cb4a/packages/auth/server/lib/utils/handle-oauth-authorize-url.ts#L41-L99) · [More projects using arctic →](https://dashboard.exa.ai/playground/search?q=arctic%20GitHub%20projects)

**Quickstart**

```javascript
import { OAuth2Client, CodeChallengeMethod, generateCodeVerifier, generateState } from "arctic";
const client = new OAuth2Client(process.env.OAUTH_CLIENT_ID, null, process.env.OAUTH_REDIRECT_URI);
const verifier = generateCodeVerifier();
const state = generateState();
const url = client.createAuthorizationURLWithPKCE(process.env.OAUTH_AUTHORIZATION_URL, state, CodeChallengeMethod.S256, verifier, ["openid"]);
console.log(url.href);

```

From [README.md](https://api.github.com/repos/pilcrowonpaper/arctic/git/blobs/11e455e699111bbc49355c51604d8edbc4fc97e6)

### react-oidc-context

[GitHub](https://github.com/authts/react-oidc-context) · [npm](https://www.npmjs.com/package/react-oidc-context) · [Docs](https://api.github.com/repos/authts/react-oidc-context/readme)

Adds OpenID Connect and OAuth2 authentication to React through the context API.

- Downloads / mo: 4.2M
- Stars: 1.0K
- Last release: 3.3.1
- License: MIT
- Capabilities: [From the react-oidc-context docs](https://api.github.com/repos/authts/react-oidc-context/readme)

```sh
npm install react-oidc-context@3.3.1 react@18 react-dom@18 oidc-client-ts@3.5.0
```

**Quickstart**

```javascript
import React from "react";
import { createRoot } from "react-dom/client";
import { AuthProvider, useAuth } from "react-oidc-context";
const host = document.createElement("div");
document.body.append(host);
function Login() { const auth = useAuth(); return <button onClick={() => void auth.signinRedirect()}>Sign in</button>; }
createRoot(host).render(<AuthProvider authority="https://issuer.example.com" client_id="registered-client" redirect_uri={window.location.origin + "/callback"} onSigninCallback={() => window.history.replaceState({}, document.title, window.location.pathname)}><Login /></AuthProvider>);

```

From [README.md](https://api.github.com/repos/authts/react-oidc-context/contents/example/index.tsx) · [Find projects using react-oidc-context →](https://dashboard.exa.ai/playground/search?q=react-oidc-context%20GitHub%20projects)

### simple-oauth2

[GitHub](https://github.com/lelylan/simple-oauth2) · [npm](https://www.npmjs.com/package/simple-oauth2) · [Docs](https://api.github.com/repos/lelylan/simple-oauth2/readme)

Provides Node.js OAuth clients for authorization-code and application token grants.

- Downloads / mo: 3.3M
- Stars: 1.6K
- Last release: 5.1.0
- License: Apache-2.0
- Capabilities: [From the simple-oauth2 docs](https://api.github.com/repos/lelylan/simple-oauth2/readme)

**Strengths**

- **Recreates persisted token objects.** Use createToken to restore an AccessToken instance from stored token data.
- **Supports early token renewal.** Pass an expiration window to expired before requesting a replacement.

**Watch out for**

- **Application tokens need replacement.** Fetch a new client-credentials token after expiry instead of using refresh.
- **Refresh decisions belong to callers.** Check expired and call refresh when the token needs renewal.

```sh
npm install simple-oauth2@5.1.0
```

**Quickstart**

```javascript
const { ClientCredentials } = require("simple-oauth2");
const client = new ClientCredentials({ client: { id: process.env.OAUTH_CLIENT_ID, secret: process.env.OAUTH_CLIENT_SECRET }, auth: { tokenHost: process.env.OAUTH_TOKEN_HOST, tokenPath: process.env.OAUTH_TOKEN_PATH } });
client.getToken({}).then((token) => console.log(token.expired())).catch(console.error);

```

From [README.md](https://api.github.com/repos/lelylan/simple-oauth2/contents/API.md) · [Find projects using simple-oauth2 →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20simple-oauth2%20for%20OAuth%20client%20flows&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

## FAQ

### Which JavaScript OAuth library should I use?

[openid-client](#openid-client) suits server code that runs full OAuth and OpenID Connect flows. [oidc-client-ts](#oidc-client-ts) suits browser apps that manage sign-in and token renewal. [passport-oauth2](#passport-oauthtwo) suits Express apps that already authenticate through Passport.

### What is PKCE?

PKCE, or Proof Key for Code Exchange, binds an authorization code to the client that requested it. The client sends a hashed secret with the authorization request and the original secret with the token request. [openid-client](#openid-client) and [oauth4webapi](#oauth-webapi) generate PKCE values.

### What is openid-client?

[openid-client](#openid-client) is an OAuth and OpenID Connect client for JavaScript runtimes. It handles issuer discovery, authorization URLs, several grant types, and PKCE.

### What is react-oidc-context?

[react-oidc-context](#react-oidc-context) wraps oidc-client-ts in a React provider and hooks. It intercepts the sign-in callback and exposes the authentication state to components.

### OAuth vs OpenID Connect: what is the difference?

OAuth grants an app access to a user's resources at another service. OpenID Connect adds an identity layer on top of OAuth with an ID token that says who the user is.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript OAuth client libraries openid-client oauth4webapi simple-oauth2 badgateway code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
