npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

oauth2-pkce-client

v1.0.0

Published

Secure OAuth2 Authorization Code Flow with PKCE implementation

Readme

OAuth2 PKCE Client

A secure, lightweight OAuth2 Authorization Code Flow with PKCE (Proof Key for Code Exchange) implementation for modern web applications.

Features

  • 🔐 Secure by Default: Implements OAuth2 Authorization Code Flow with PKCE
  • 🚀 Lightweight: Zero runtime dependencies, < 10KB gzipped
  • ⚛️ React Support: Built-in React hooks and context provider
  • 🔄 Auto Token Refresh: Automatic token refresh before expiry
  • 📦 TypeScript: Full TypeScript support with type definitions
  • 🌳 Tree-shakeable: Import only what you need
  • 🧪 Well Tested: Comprehensive test coverage
  • 🎯 Framework Agnostic: Works with any JavaScript framework

Installation

npm install oauth2-pkce-client
# or
yarn add oauth2-pkce-client
# or
pnpm add oauth2-pkce-client

Quick Start

Vanilla JavaScript

import { OAuth2Service } from 'oauth2-pkce-client';

const oauth = new OAuth2Service({
  clientId: 'your-client-id',
  authorizationEndpoint: 'https://auth.example.com/authorize',
  tokenEndpoint: 'https://auth.example.com/token',
  redirectUri: 'http://localhost:3000/callback',
  scope: 'openid profile email',
});

// Start login
await oauth.authorize();

// Handle callback (automatically called on redirect URI)
// Tokens are automatically stored

// Check authentication
if (oauth.isAuthenticated()) {
  const token = oauth.getAccessToken();
  // Use token for API calls
}

// Logout
oauth.logout();

React

import { OAuth2Provider, useAuth } from 'oauth2-pkce-client';

// Wrap your app with OAuth2Provider
function App() {
  const config = {
    clientId: 'your-client-id',
    authorizationEndpoint: 'https://auth.example.com/authorize',
    tokenEndpoint: 'https://auth.example.com/token',
    redirectUri: 'http://localhost:3000/callback',
    scope: 'openid profile email',
  };

  return (
    <OAuth2Provider config={config}>
      <YourApp />
    </OAuth2Provider>
  );
}

// Use the auth hook in components
function LoginButton() {
  const { isAuthenticated, login, logout, getToken } = useAuth();

  if (isAuthenticated) {
    return <button onClick={() => logout()}>Logout</button>;
  }

  return <button onClick={() => login()}>Login</button>;
}

API Reference

OAuth2Service

The main class for handling OAuth2 authentication.

Constructor

new OAuth2Service(config: OAuth2Config)

Configuration Options

| Option | Type | Required | Description | |--------|------|----------|-------------| | clientId | string | ✅ | OAuth2 client ID | | authorizationEndpoint | string | ✅ | Authorization server's authorize endpoint | | tokenEndpoint | string | ✅ | Authorization server's token endpoint | | redirectUri | string | ✅ | Redirect URI registered with OAuth2 provider | | scope | string | ❌ | Space-delimited list of scopes | | logoutEndpoint | string | ❌ | Optional logout endpoint | | autoRefresh | boolean | ❌ | Enable automatic token refresh (default: true) | | refreshBufferTime | number | ❌ | Seconds before expiry to refresh (default: 300) | | storage | Storage | ❌ | Custom storage implementation (default: localStorage) | | debug | boolean | ❌ | Enable debug logging |

Methods

  • authorize(additionalParams?): Start the authorization flow
  • handleCallback(url?): Handle OAuth2 callback (called automatically)
  • refreshAccessToken(): Manually refresh the access token
  • getAccessToken(): Get current access token
  • getRefreshToken(): Get current refresh token
  • getIdToken(): Get ID token (if available)
  • isAuthenticated(): Check if user is authenticated
  • getAuthState(): Get complete authentication state
  • logout(redirectTo?): Logout user

React Hooks

useOAuth2

const {
  isAuthenticated,
  isLoading,
  accessToken,
  refreshToken,
  error,
  login,
  logout,
  refreshToken,
  getToken,
} = useOAuth2(config);

useAuth

Must be used within OAuth2Provider:

const auth = useAuth();

Advanced Usage

Custom Storage

import { OAuth2Service } from 'oauth2-pkce-client';

const oauth = new OAuth2Service({
  // ... other config
  storage: sessionStorage, // Use sessionStorage instead of localStorage
});

Additional Authorization Parameters

// Pass additional parameters to the authorization request
await oauth.authorize({
  prompt: 'consent',
  login_hint: '[email protected]',
});

Token Refresh Callbacks

const oauth = new OAuth2Service({
  // ... other config
  onTokenRefresh: (tokens) => {
    console.log('Tokens refreshed:', tokens);
  },
  onAuthStateChange: (isAuthenticated) => {
    console.log('Auth state changed:', isAuthenticated);
  },
});

Security Considerations

This library implements several security best practices:

  1. PKCE (RFC 7636): Protects against authorization code interception attacks
  2. State Parameter: Prevents CSRF attacks
  3. Secure Token Storage: Tokens stored in configurable storage (localStorage/sessionStorage)
  4. Automatic Token Expiry: Tokens are automatically cleared when expired
  5. XSS Protection: No tokens in URLs or global scope

Browser Support

  • Chrome/Edge 91+
  • Firefox 89+
  • Safari 15+
  • Opera 77+

Requires native Crypto API support for PKCE.

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

License

MIT © Jeremy Walters

Links