Official JavaScript SDK for LicenseChain - Secure license management for web applications.
Note: This is the browser/isomorphic LicenseChain-JavaScript-SDK. For server-only Node.js, use LicenseChain-NodeJS-SDK. See docs.licensechain.app.
- Canonical API base:
https://api.licensechain.app/v1 - API docs: docs.licensechain.app
Root exports match @licensechain/nodejs-sdk: verifyLicenseAssertionJwt, LICENSE_TOKEN_USE_CLAIM, and VerifyLicenseAssertionOptions (TypeScript). Use them after LicenseService.verifyWithDetails when the API returns license_token and license_jwks_uri.
import { verifyLicenseAssertionJwt } from '@licensechain/javascript-sdk'; // or: const { verifyLicenseAssertionJwt } = require('@licensechain/javascript-sdk');
jose is a runtime dependency (listed in package.json); CJS/ESM builds load it from node_modules. Legacy require('@licensechain/javascript-sdk/license-assertion.cjs') still works and delegates to the same implementation.
UMD / CDN: dist/index.umd.js treats jose as external; browser bundles that call verifyLicenseAssertionJwt must load a compatible jose build or use ESM with a bundler that resolves jose. Prefer Node or bundled ESM for JWT verification in production.
- ๐ Secure Authentication - User registration, login, and session management
- ๐ License Management - Create, validate, update, and revoke licenses
- ๐ก๏ธ Hardware ID Validation - Prevent license sharing and unauthorized access
- ๐ Webhook Support - Real-time license events and notifications
- ๐ Analytics Integration - Track license usage and performance metrics
- โก High Performance - Optimized for production workloads
- ๐ Async Operations - Non-blocking HTTP requests and data processing
- ๐ ๏ธ Easy Integration - Simple API with comprehensive documentation
# Install via npm npm install @licensechain/javascript-sdk # Or via yarn yarn add @licensechain/javascript-sdk
<!-- ES6 Module --> <script type="module"> import LicenseChain from 'https://cdn.skypack.dev/@licensechain/javascript-sdk'; </script> <!-- UMD --> <script src="https://unpkg.com/@licensechain/javascript-sdk/dist/index.umd.js"></script>
- Download the latest release from GitHub Releases
- Include the script in your HTML
- Use the global
LicenseChainobject
import LicenseChain from '@licensechain/javascript-sdk'; // Initialize the client const client = new LicenseChain({ apiKey: 'your-api-key', appName: 'your-app-name', version: '1.0.0', baseUrl: 'https://api.licensechain.app/v1' }); // Connect to LicenseChain try { await client.connect(); console.log('Connected to LicenseChain successfully!'); } catch (error) { console.error('Failed to connect:', error.message); }
// Register a new user try { const user = await client.register('username', 'password', '[email protected]'); console.log('User registered successfully!'); console.log('User ID:', user.id); } catch (error) { console.error('Registration failed:', error.message); } // Login existing user try { const user = await client.login('username', 'password'); console.log('User logged in successfully!'); console.log('Session ID:', user.sessionId); } catch (error) { console.error('Login failed:', error.message); }
// Validate a license try { const license = await client.validateLicense('LICENSE-KEY-HERE'); console.log('License is valid!'); console.log('License Key:', license.key); console.log('Status:', license.status); console.log('Expires:', license.expires); console.log('Features:', license.features.join(', ')); console.log('User:', license.user); } catch (error) { console.error('License validation failed:', error.message); } // Get user's licenses try { const licenses = await client.getUserLicenses(); console.log(`Found ${licenses.length} licenses:`); licenses.forEach((license, index) => { console.log(` ${index + 1}. ${license.key} - ${license.status} (Expires: ${license.expires})`); }); } catch (error) { console.error('Failed to get licenses:', error.message); }
// Get hardware ID (automatically generated) const hardwareId = client.getHardwareId(); console.log('Hardware ID:', hardwareId); // Validate hardware ID with license try { const isValid = await client.validateHardwareId('LICENSE-KEY-HERE', hardwareId); if (isValid) { console.log('Hardware ID is valid for this license!'); } else { console.log('Hardware ID is not valid for this license.'); } } catch (error) { console.error('Hardware ID validation failed:', error.message); }
// Set up webhook handler client.setWebhookHandler((event, data) => { console.log('Webhook received:', event); switch (event) { case 'license.created': console.log('New license created:', data.licenseKey); break; case 'license.updated': console.log('License updated:', data.licenseKey); break; case 'license.revoked': console.log('License revoked:', data.licenseKey); break; } }); // Start webhook listener await client.startWebhookListener();
All endpoints target the LicenseChain HTTP API at https://api.licensechain.app/v1. The client accepts either the canonical /v1 base or the root host and normalizes requests to the same API version.
| Method | Endpoint | Description |
|---|---|---|
| GET | /v1/health | Health check |
| POST | /v1/auth/login | User login |
| POST | /v1/auth/register | User registration |
| GET | /v1/apps | List applications |
| POST | /v1/apps | Create application |
| GET | /v1/licenses | List licenses |
| POST | /v1/licenses/verify | Verify license |
| GET | /v1/webhooks | List webhooks |
| POST | /v1/webhooks | Create webhook |
| GET | /v1/analytics | Get analytics |
See the LicenseChain SDK docs for full HTTP and client method reference. Repository examples and inline docs cover language-specific usage.
const client = new LicenseChain({ apiKey: 'your-api-key', appName: 'your-app-name', version: '1.0.0', baseUrl: 'https://api.licensechain.app/v1' // Optional });
// Connect to LicenseChain await client.connect(); // Disconnect from LicenseChain await client.disconnect(); // Check connection status const isConnected = client.isConnected();
// Register a new user const user = await client.register(username, password, email); // Login existing user const user = await client.login(username, password); // Logout current user await client.logout(); // Get current user info const user = await client.getCurrentUser();
// Validate a license const license = await client.validateLicense(licenseKey); // Get user's licenses const licenses = await client.getUserLicenses(); // Create a new license const license = await client.createLicense(userId, features, expires); // Update a license const license = await client.updateLicense(licenseKey, updates); // Revoke a license await client.revokeLicense(licenseKey); // Extend a license const license = await client.extendLicense(licenseKey, days);
// Get hardware ID const hardwareId = client.getHardwareId(); // Validate hardware ID const isValid = await client.validateHardwareId(licenseKey, hardwareId); // Bind hardware ID to license await client.bindHardwareId(licenseKey, hardwareId);
// Set webhook handler client.setWebhookHandler(handler); // Start webhook listener await client.startWebhookListener(); // Stop webhook listener await client.stopWebhookListener();
// Track event await client.trackEvent(eventName, properties); // Get analytics data const analytics = await client.getAnalytics(timeRange);
Set these in your environment or through your build process:
# Required export LICENSECHAIN_API_KEY=your-api-key export LICENSECHAIN_APP_NAME=your-app-name export LICENSECHAIN_APP_VERSION=1.0.0 # Optional export LICENSECHAIN_BASE_URL=https://api.licensechain.app/v1 export LICENSECHAIN_DEBUG=true
const client = new LicenseChain({ apiKey: 'your-api-key', appName: 'your-app-name', version: '1.0.0', baseUrl: 'https://api.licensechain.app/v1', timeout: 30000, // Request timeout in milliseconds retries: 3, // Number of retry attempts debug: false, // Enable debug logging userAgent: 'MyApp/1.0.0' // Custom user agent });
The SDK automatically generates and manages hardware IDs to prevent license sharing:
// Hardware ID is automatically generated and stored const hardwareId = client.getHardwareId(); // Validate against license const isValid = await client.validateHardwareId(licenseKey, hardwareId);
- All API requests use HTTPS
- API keys are securely stored and transmitted
- Session tokens are automatically managed
- Webhook signatures are verified
- Real-time license validation
- Hardware ID binding
- Expiration checking
- Feature-based access control
// Track custom events await client.trackEvent('app.started', { level: 1, playerCount: 10 }); // Track license events await client.trackEvent('license.validated', { licenseKey: 'LICENSE-KEY', features: 'premium,unlimited' });
// Get performance metrics const metrics = await client.getPerformanceMetrics(); console.log('API Response Time:', metrics.averageResponseTime + 'ms'); console.log('Success Rate:', (metrics.successRate * 100).toFixed(2) + '%'); console.log('Error Count:', metrics.errorCount);
try { const license = await client.validateLicense('invalid-key'); } catch (error) { if (error instanceof LicenseChainError) { switch (error.type) { case 'INVALID_LICENSE': console.error('License key is invalid'); break; case 'EXPIRED_LICENSE': console.error('License has expired'); break; case 'NETWORK_ERROR': console.error('Network connection failed'); break; default: console.error('LicenseChain error:', error.message); } } }
// Automatic retry for network errors const client = new LicenseChain({ apiKey: 'your-api-key', appName: 'your-app-name', version: '1.0.0', retries: 3, // Retry up to 3 times timeout: 30000 // Wait 30 seconds for each request });
# Run tests npm test # Run tests with coverage npm run test:coverage # Run tests in watch mode npm run test:watch
# Test with real API
npm run test:integrationSee the examples/ directory for complete examples:
basic-usage.js- Basic SDK usageadvanced-features.js- Advanced features and configurationwebhook-integration.js- Webhook handling
We welcome contributions! Please see our Contributing Guide for details.
- Clone the repository
- Install Node.js 20 or later
- Install dependencies:
npm install - Build:
npm run build - Test:
npm test
This project is licensed under the MIT License (ELv2) โ see the LICENSE file for details.
- Documentation: https://docs.licensechain.app/en/sdk
- Issues: GitHub Issues
- Discord: LicenseChain Discord
- Email: [email protected]
Made with โค๏ธ for the JavaScript community