vineeth-unified-oauth
v1.0.0
Published
A unified OAuth library supporting multiple providers (Google, Facebook, LinkedIn, Twitter, Instagram, Reddit, and GitHub)
Maintainers
Readme
Unified OAuth
A unified OAuth library supporting multiple providers with TypeScript support, framework-agnostic design, and robust error handling.
Supported Providers
- GitHub
Features
- 🔒 Secure OAuth 2.0 implementation with PKCE support
- 🎯 TypeScript-first with full type definitions
- 🌐 Framework-agnostic - works in Node.js and browsers
- 🛠 Configurable redirect URIs, scopes, and custom parameters
- 🚨 Robust error handling with custom error classes
- 📦 ESM + CJS builds for maximum compatibility
- 🔄 Token refresh and revocation support
Installation
npm install unified-oauthFor Node.js environments, you'll also need to install node-fetch:
npm install node-fetchQuick Start
Getting OAuth Credentials
Before using this library, you need to obtain OAuth credentials from each provider:
- Google: Google Cloud Console → APIs & Services → Credentials
- GitHub: GitHub Settings → Developer settings → OAuth Apps
- Facebook: Facebook Developers → My Apps
- LinkedIn: LinkedIn Developer Portal
- Twitter: Twitter Developer Portal
- Instagram: Instagram Basic Display
- Reddit: Reddit App Preferences
Method 1: Direct Configuration
import GoogleOAuth from 'unified-oauth/google';
const googleAuth = new GoogleOAuth({
clientId: 'your-google-client-id',
clientSecret: 'your-google-client-secret',
redirectUri: 'http://localhost:3000/callback',
scopes: ['openid', 'profile', 'email']
});
// Generate authorization URL
const authUrl = googleAuth.generateAuthorizationUrl({
state: 'random-state-string'
});
// Exchange code for token
const tokenResponse = await googleAuth.exchangeCodeForToken({
code: 'authorization-code-from-callback'
});
// Get user info
const userInfo = await googleAuth.getUserInfo(tokenResponse.accessToken);Method 2: Environment Variables (Recommended)
Create a .env file in your project:
# .env file
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://localhost:3000/callback
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
GITHUB_REDIRECT_URI=http://localhost:3000/callbackThen use the fromEnv method:
import GoogleOAuth from 'unified-oauth/google';
// Automatically loads from environment variables
const googleAuth = GoogleOAuth.fromEnv();
// Or with overrides
const googleAuth = GoogleOAuth.fromEnv({
scopes: ['openid', 'profile', 'email', 'https://www.googleapis.com/auth/calendar']
});GitHub OAuth
import GitHubOAuth from 'unified-oauth/github';
const githubAuth = new GitHubOAuth({
clientId: 'your-github-client-id',
clientSecret: 'your-github-client-secret',
redirectUri: 'http://localhost:3000/callback'
});
const authUrl = githubAuth.generateAuthorizationUrl();Using PKCE (Proof Key for Code Exchange)
import GoogleOAuth from 'unified-oauth/google';
const googleAuth = new GoogleOAuth({
clientId: 'your-google-client-id',
clientSecret: 'your-google-client-secret',
redirectUri: 'http://localhost:3000/callback'
});
// Generate authorization URL with PKCE
const { url, codeVerifier } = await googleAuth.generateAuthorizationUrlWithPKCE();
// Store codeVerifier securely (e.g., in session)
// Redirect user to url
// Later, exchange code for token with PKCE
const tokenResponse = await googleAuth.exchangeCodeForToken({
code: 'authorization-code-from-callback',
codeVerifier: codeVerifier
});Configuration
OAuthConfig
interface OAuthConfig {
clientId: string;
clientSecret: string;
redirectUri: string;
scopes?: string[];
state?: string;
customParams?: Record<string, string>;
}Client Options
interface OAuthClientOptions {
timeout?: number; // Request timeout in milliseconds (default: 10000)
userAgent?: string; // Custom user agent (default: 'unified-oauth/1.0.0')
customHeaders?: Record<string, string>; // Additional headers for requests
}Error Handling
The library provides specific error classes for different scenarios:
import {
OAuthError,
ConfigurationError,
AuthorizationError,
TokenExchangeError,
UserInfoError,
NetworkError,
TimeoutError,
InvalidTokenError
} from 'unified-oauth';
try {
const tokenResponse = await googleAuth.exchangeCodeForToken({ code });
} catch (error) {
if (error instanceof TokenExchangeError) {
console.error('Token exchange failed:', error.message);
console.error('Status code:', error.statusCode);
console.error('Response:', error.response);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.message);
}
}Provider-Specific Usage
All Providers
// Import specific providers
import GoogleOAuth from 'unified-oauth/google';
import FacebookOAuth from 'unified-oauth/facebook';
import GitHubOAuth from 'unified-oauth/github';
import LinkedInOAuth from 'unified-oauth/linkedin';
import TwitterOAuth from 'unified-oauth/twitter';
import InstagramOAuth from 'unified-oauth/instagram';
import RedditOAuth from 'unified-oauth/reddit';
// Or import from main package
import {
GoogleOAuth,
FacebookOAuth,
GitHubOAuth
} from 'unified-oauth';Default Scopes by Provider
- Google:
['openid', 'profile', 'email'] - Facebook:
['email', 'public_profile'] - GitHub:
['user:email'] - LinkedIn:
['r_liteprofile', 'r_emailaddress'] - Twitter:
['tweet.read', 'users.read'] - Instagram:
['user_profile'] - Reddit:
['identity']
API Reference
Methods
generateAuthorizationUrl(params?)
Generates the OAuth authorization URL.
generateAuthorizationUrlWithPKCE(params?)
Generates the OAuth authorization URL with PKCE support.
exchangeCodeForToken(params)
Exchanges authorization code for access token.
refreshToken(params)
Refreshes an expired access token.
getUserInfo(accessToken)
Fetches user information using the access token.
revokeToken(params)
Revokes an access token (if supported by provider).
License
MIT
Contributing
Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.
Support
If you encounter any issues or have questions, please file an issue on our GitHub repository.
