Reclaim Identity JS SDK
Reclaim Identity is a JavaScript SDK that provides seamless integration with Reclaim Protocol's authentication system. The SDK manages OAuth 2.0 flows, popup windows, token management, and user session handling.
Features
- Simple OAuth 2.0 authentication flow
- Popup-based authentication
- Secure token management with httpOnly cookies
- Event-based state management
- CSRF protection
- Session handling
- AMD module support
- Singleton pattern implementation
Installation
NPM
npm install @reclaim/identity-js
CDN
Include directly via CDN:
<script src="https://unpkg.com/@reclaim/identity-js@latest"></script>
Usage
Initialization
const clientId = 'your-client-id';
const clientSecret = 'your-client-secret'
const redirectUri = 'your-redirect-uri';
const reclaimAuth = getReclaimAuth(clientId, clientSecret,redirectUri);
Authentication
reclaimAuth.signIn()
.then(user => {
console.log('Signed in:', user);
})
.catch(error => {
if (error.message.includes('popup')) {
console.error('Popup was blocked');
} else {
console.error('Authentication error:', error);
}
});
reclaimAuth.signOut()
.then(() => {
console.log('Signed out successfully');
})
.catch(error => {
console.error('Sign out error:', error);
});
const user = reclaimAuth.getCurrentUser();
const unsubscribe = reclaimAuth.onAuthStateChanged(user => {
if (user) {
console.log('User state changed:', user);
} else {
console.log('User signed out');
}
});
unsubscribe();
Complete Browser Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reclaim Identity Demo</title>
</head>
<body>
<div>
<button id="signInBtn">Sign In</button>
<button id="signOutBtn">Sign Out</button>
<div id="userInfo"></div>
</div>
<script src="https://unpkg.com/@reclaim/identity-js@latest"></script>
<script>
const auth = getReclaimAuth(
'your-client-id',
'your-redirect-uri'
);
auth.onAuthStateChanged(user => {
const userInfo = document.getElementById('userInfo');
if (user) {
userInfo.textContent = JSON.stringify(user, null, 2);
} else {
userInfo.textContent = 'No user signed in';
}
});
document.getElementById('signInBtn').addEventListener('click', async () => {
try {
const user = await auth.signIn();
console.log('Signed in successfully:', user);
} catch (error) {
console.error('Sign in failed:', error);
}
});
document.getElementById('signOutBtn').addEventListener('click', async () => {
try {
await auth.signOut();
console.log('Signed out successfully');
} catch (error) {
console.error('Sign out failed:', error);
}
});
</script>
</body>
</html>
API Reference
getReclaimAuth(clientId: string, clientSecret: string, redirectUri: string)
Returns a singleton instance of the ReclaimAuth class. Both parameters are required for initial setup.
auth.signIn(): Promise
Initiates the authentication flow by opening a popup window. Returns a promise that resolves with the user data.
auth.signOut(): Promise
Signs out the current user and clears authentication state.
auth.getCurrentUser(): User | null
Returns the currently authenticated user or null if not authenticated.
auth.onAuthStateChanged(callback: (user: User | null) => void): () => void
Subscribes to authentication state changes. Returns an unsubscribe function.
Configuration
The SDK uses the following defaults:
{
apiBaseUrl: 'https://identity.reclaimprotocol.org',
env: 'production',
popupWidth: 600,
popupHeight: 600
}
Security Features
- CSRF protection using state parameter
- Secure cookie handling
- Origin validation for popup messages
- Cross-window communication security
- Credentials included in API requests
Browser Compatibility
The SDK requires browsers with support for:
- Web Crypto API for secure random values
- Fetch API for network requests
- PostMessage API for popup communication
- ES6+ features (can be polyfilled)
- Cookies
Error Handling
Common error scenarios:
try {
await auth.signIn();
} catch (error) {
switch (true) {
case error.message.includes('popup'):
break;
case error.message.includes('code'):
break;
case error.message.includes('token'):
break;
default:
}
}
Advanced Usage
Custom Event Handling
class AuthenticationManager {
constructor() {
this.auth = getReclaimAuth(clientId, clientSecret, redirectUri);
this.setupAuthListeners();
}
setupAuthListeners() {
this.unsubscribe = this.auth.onAuthStateChanged(user => {
if (user) {
this.handleSignedIn(user);
} else {
this.handleSignedOut();
}
});
}
async handleSignedIn(user) {
}
async handleSignedOut() {
}
cleanup() {
this.unsubscribe();
}
}
Best Practices
-
Error Handling
- Always implement proper error handling for authentication operations
- Handle popup blocking scenarios
- Implement proper cleanup for event listeners
-
Security
- Use HTTPS in production
- Store client credentials securely
- Implement proper CORS settings
- Validate authentication state consistently
-
User Experience
- Handle loading states during authentication
- Provide clear feedback for authentication errors
- Implement proper session management
- Handle page refreshes gracefully
Troubleshooting
Common issues and solutions:
-
Popup Blocked
- Ensure signIn is called in response to user action
- Check browser popup settings
-
Authentication Failures
- Verify clientId and redirectUri
- Check network requests
- Verify cookie settings
-
Security Errors
- Check origin settings
- Verify CORS configuration
- Validate SSL certificates
Support
For issues, questions, or feature requests:
License
MIT License - see LICENSE for details
Contributing
Contributions are welcome! Please read our contributing guidelines for details.