Package Exports
- trustlabs-sdk
- trustlabs-sdk/client
- trustlabs-sdk/package.json
- trustlabs-sdk/styles
Readme
TrustLabs SDK
An easy-to-use JavaScript SDK for displaying trust verification badges on your website. Works with React, Vue, vanilla JavaScript, and can be loaded via CDN.
🚀 Quick Start
1. CDN (Fastest Setup)
<!-- Add meta tags for auto-configuration -->
<meta name="trustlabs-endpoint" content="http://localhost:8080/api/public/trust-status">
<meta name="trustlabs-auto-render" content="true">
<!-- Load the SDK -->
<script src="https://unpkg.com/trustlabs-sdk@latest/dist/sdk.min.js"></script>
<!-- Mark emails with trust-email class -->
<span class="trust-email">user@example.com</span>2. NPM Installation
npm install trustlabs-sdk3. React/Next.js
import { TrustBadge, init } from 'trustlabs-sdk';
// Initialize once in your app
init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
function UserProfile({ email }) {
return (
<div>
<span>{email}</span>
<TrustBadge emails={[email]} />
</div>
);
}📋 Table of Contents
🔧 Server Setup
Important: Your API key must never be exposed in client-side code. Set up a server proxy:
Next.js (Recommended)
// app/api/trust-status/route.ts
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
const { emails } = await req.json();
const apiKey = process.env.TRUSTLABS_API_KEY;
const params = emails.map(encodeURIComponent).join(',');
const response = await fetch(
`https://api.trustlabs.pro/api/public/trust-status?emails=${params}`,
{ headers: { 'X-API-Key': apiKey } }
);
const data = await response.json();
return NextResponse.json(data.results);
}🎯 Usage Examples
Simple Auto-Detection
The easiest way - just add CSS classes:
<script src="https://unpkg.com/trustlabs-sdk@latest/dist/sdk.min.js"></script>
<script>
// One-time setup
window.TrustLabsSDK.init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
// Auto-render all emails with .trust-email class
window.TrustLabsSDK.autoRender();
</script>
<!-- Emails will automatically get badges -->
<p>Contact: <span class="trust-email">support@company.com</span></p>
<p>CEO: <span class="trust-email">ceo@company.com</span></p>React Component
Basic Usage
import { TrustBadge, init, TrustLabsError } from 'trustlabs-sdk';
// Initialize once at app level
init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
function UserCard({ user }) {
return (
<div>
<h3>{user.name}</h3>
<div>
<span>{user.email}</span>
<TrustBadge
emails={[user.email]}
onError={(error) => {
if (error instanceof TrustLabsError) {
console.log('Badge error:', error.code, error.details);
}
}}
/>
</div>
</div>
);
}Performance-Optimized Usage (Recommended for Large Lists)
import React, { useCallback, memo } from 'react';
import { TrustBadge, TrustBadgeProvider, TrustLabsError } from 'trustlabs-sdk';
// Wrap component with memo to prevent unnecessary re-renders
const OptimizedUserCard = memo(({ user, onError, onLoad }) => {
return (
<div>
<h3>{user.name}</h3>
<div>
<span>{user.email}</span>
<TrustBadge
emails={[user.email]}
onError={onError}
onLoad={onLoad}
/>
</div>
</div>
);
});
function UserList({ users }) {
// Memoize callbacks to prevent unnecessary re-renders
const handleError = useCallback((error: Error) => {
if (error instanceof TrustLabsError) {
console.log('Badge error:', error.code, error.details);
}
}, []);
const handleLoad = useCallback((data) => {
console.log('Badge loaded:', data);
}, []);
return (
<TrustBadgeProvider>
<div>
{users.map((user) => (
<OptimizedUserCard
key={user.id}
user={user}
onError={handleError}
onLoad={handleLoad}
/>
))}
</div>
</TrustBadgeProvider>
);
}Manual Control
// Initialize
window.TrustLabsSDK.init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
// Render specific badges
await window.TrustLabsSDK.sdk.renderBadgeWithFetch({
targetEl: document.getElementById('email-element'),
emails: ['user@example.com']
});
// Batch processing for better performance
const emails = ['user1@example.com', 'user2@example.com'];
const trustData = await window.TrustLabsSDK.getTrustStatus(emails);
emails.forEach((email, i) => {
window.TrustLabsSDK.renderTrustBadge({
targetEl: document.querySelector(`[data-email="${email}"]`),
trustData: [trustData[i]]
});
});Vue.js Integration
<template>
<div>
<span>{{ email }}</span>
<span ref="badgeTarget"></span>
</div>
</template>
<script>
import { init } from 'trustlabs-sdk';
export default {
props: ['email'],
async mounted() {
// Initialize SDK if not already done
if (!window.TrustLabsSDK?.isInitialized()) {
init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
}
// Render badge
await window.TrustLabsSDK.sdk.renderBadgeWithFetch({
targetEl: this.$refs.badgeTarget,
emails: [this.email]
});
}
}
</script>🔧 Configuration Options
Simple Configuration
window.TrustLabsSDK.init({
endpoint: 'http://localhost:8080/api/public/trust-status', // Your server endpoint
autoInjectStyles: true, // Auto-inject CSS (default: true)
});Advanced Configuration
window.TrustLabsSDK.init({
// Custom proxy function for full control
proxy: async (emails) => {
const response = await fetch('/custom-endpoint', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ emails })
});
return response.json();
},
// Default options for all renders
defaultOptions: {
showTooltip: true
}
});📚 API Reference
Initialization
// Simple initialization
window.TrustLabsSDK.init({ endpoint: 'http://localhost:8080/api/public/trust-status' });
// Advanced initialization
window.TrustLabsSDK.init({
endpoint: 'http://localhost:8080/api/public/trust-status', // Your server endpoint
proxy: customProxyFunction, // Custom proxy (overrides endpoint)
autoInjectStyles: true, // Auto-inject CSS
defaultOptions: {} // Default render options
});Core Functions
// Check if initialized
window.TrustLabsSDK.isInitialized() // => boolean
// Auto-render emails with CSS selector
await window.TrustLabsSDK.autoRender('.trust-email')
// Get trust status data
const data = await window.TrustLabsSDK.getTrustStatus(['user@example.com'])
// Render badge with existing data
window.TrustLabsSDK.renderTrustBadge({
targetEl: element,
trustData: data
})
// Render badge with automatic data fetching
await window.TrustLabsSDK.sdk.renderBadgeWithFetch({
targetEl: element,
emails: ['user@example.com']
})React Component
<TrustBadge
emails={['user@example.com']} // Required: array of emails
showTooltip={true} // Optional: show completion date
onError={(error) => {}} // Optional: error callback
onLoad={(data) => {}} // Optional: success callback
/>⚠️ Error Handling
The SDK provides comprehensive error handling with specific error codes:
import { TrustLabsError } from 'trustlabs-sdk';
try {
await window.TrustLabsSDK.getTrustStatus(['invalid-email']);
} catch (error) {
if (error instanceof TrustLabsError) {
console.log('Error code:', error.code);
console.log('Error details:', error.details);
switch (error.code) {
case 'NOT_CONFIGURED':
// SDK not initialized
break;
case 'INVALID_EMAIL_FORMAT':
// Invalid email addresses
break;
case 'NETWORK_ERROR':
// Network/API issues
break;
}
}
}Error Codes
NOT_CONFIGURED: SDK not initialized or proxy not setINVALID_INPUT: Missing or invalid input parametersINVALID_EMAIL_FORMAT: Invalid email address formatTOO_MANY_EMAILS: More than 100 emails in single requestNETWORK_ERROR: Network or API communication errorINVALID_RESPONSE: Unexpected response format from server
📁 Examples
Live examples available in the examples/ directory:
- Simple CDN Usage - Quickest setup
- Advanced CDN Features - All CDN features
- React/Next.js - React component usage
- Server Setup Guide - Multiple backend examples
🎨 Styling
Default Styles
The SDK includes beautiful default styles that work out of the box:
.trust-badge {
display: inline-block;
margin-left: 6px;
/* Additional default styles included */
}
.trust-badge.verified {
/* Styles for verified badges */
}
.trust-badge.loading {
/* Loading animation */
}
.trust-badge.error {
/* Error state styles */
}Custom Styling
Override styles using CSS specificity:
/* Override badge spacing */
.my-container .trust-badge {
margin-left: 10px;
}
/* Custom verified badge style */
.trust-badge.verified img {
filter: hue-rotate(90deg); /* Green tint */
}🌍 Browser Support
| Browser | Version |
|---|---|
| Chrome | 60+ |
| Firefox | 55+ |
| Safari | 12+ |
| Edge | 79+ |
📦 Bundle Sizes
| Build | Size (gzipped) |
|---|---|
| UMD | ~8KB |
| ESM | ~6KB |
| React | ~4KB |
🔄 Migration Guide
From v2.x to v3.x
// OLD (v2.x)
import { setApiKey, getTrustStatus } from 'trustlabs-sdk';
setApiKey('your-api-key'); // ❌ Insecure
// NEW (v3.x)
import { init } from 'trustlabs-sdk';
init({ endpoint: 'http://localhost:8080/api/public/trust-status' }); // ✅ SecureLegacy Support
v3.x maintains backward compatibility for the setProxy API:
// Still works in v3.x
window.TrustLabsSDK.setProxy(async (emails) => {
// Your proxy function
});🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
- 📧 Email: support@trustlabs.pro
- 🐛 Issues: GitHub Issues
- 📖 Documentation: GitHub Wiki
Made with ❤️ by the TrustLabs team