Web SDK Reference

Production-ready face verification and liveness detection SDK for web applications.

✨ Features

  • 🎭 Real-time Face Detection - Powered by optimized ML models
  • 🔐 Liveness Detection - Anti-spoofing with passive detection
  • 🚀 Zero Dependencies - All assets bundled, no external CDNs
  • 📦 Lightweight - ~10MB total (loaded on-demand)
  • 🔒 Privacy First - All processing happens on-device
  • 🌐 Browser Support - Works in all modern browsers
  • 📱 Mobile Ready - Optimized for mobile devices
  • 🎯 TypeScript Support - Full type definitions included

🚀 Quick Start

Installation

npm install legitface-sdk-web

Basic Usage

UMD (Script Tag)

<!DOCTYPE html>
<html>
<head>
  <!-- Important: Include id="lf-sdk-script" for auto-detection -->
  <script id="lf-sdk-script" src="node_modules/legitface-sdk-web/dist/legitface-sdk.umd.js"></script>
</head>
<body>
  <div id="legitface-container"></div>

  <script>
    const apiUrl = 'https://api.yourservice.com';
		const sessionId = 'user-session-123';

    const sdk = new LegitFaceSDK({
      sessionId: apiUrl,
      apiUrl: sessionId,
      debug: true
    });

    // Initialize with options
    sdk.init({
      processOnBackend: async () => {
        return true;
      },
      onComplete: (result) => {
        console.log('Verification complete:', result);
      }
    });
  </script>
</body>
</html>

ES Module

import LegitFaceSDK from 'legitface-sdk-web';

const apiUrl = 'https://api.yourservice.com';
const sessionId = 'user-session-123'

const sdk = new LegitFaceSDK({
  sessionId: sessionId,
  apiUrl: apiUrl,
  debug: true
});

// Customize UI theme
sdk.setTheme({
  accentColor: '#4F46E5',
  accentTextColor: '#FFFFFF',
  strokeWidth: 3
});

// Initialize and start
sdk.init({
  processOnBackend: async () => {
    return true;
  },
  onComplete: (result) => {
    console.log('Verification complete:', result);
  }
});

// Listen to errors
sdk.addEventListener('legitface-error', (event) => {
  console.error('SDK error:', event.detail);
});

React Example

import { useEffect, useRef, useState } from 'react';
import LegitFaceSDK from 'legitface-sdk-web';

function FaceVerification() {
  const sdkRef = useRef(null);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Load script with proper ID for auto-detection
    const script = document.createElement('script');
    const apiUrl = 'https://api.yourservice.com';
		const sessionId = `session-${Date.now()}`;

    script.id = 'lf-sdk-script';
    script.src = '/node_modules/legitface-sdk-web/dist/legitface-sdk.umd.js';
    script.onload = () => {
      const sdk = new window.LegitFaceSDK({
        sessionId: sessionId,
        apiUrl: apiUrl,
        debug: true
      });

      sdk.setTheme({
        accentColor: '#4F46E5',
        accentTextColor: '#FFFFFF'
      });

      sdk.addEventListener('legitface-error', (event) => {
        setError(event.detail);
      });

      sdk.init({
        processOnBackend: async () => {
          return true;
  			},
        onComplete: (verificationResult) => {
          setResult(verificationResult);
        }
      });

      sdkRef.current = sdk;
    };

    document.head.appendChild(script);

    return () => {
      document.head.removeChild(script);
    };
  }, []);

  return (
    <div>
      <h2>Face Verification</h2>
      <div id="legitface-container"></div>
      {result && <p>Verification: {JSON.stringify(result)}</p>}
      {error && <p style={{ color: 'red' }}>Error: {error.type}</p>}
    </div>
  );
}

📝 API Reference

Constructor

new LegitFaceSDK(config: LegitFaceConfig)

Config

OptionTypeRequiredDefaultDescription
sessionIdstringYes-Unique identifier for the verification session
apiUrlstringYes-API endpoint URL for backend communication
debugbooleanNofalseEnable debug logging
versionstringNo"latest"SDK version override

Important: Assets are auto-loaded from the script's location. Make sure to include id="lf-sdk-script" on your script tag!


Methods

init(options)

Initialize the SDK orchestrator and start the verification process.

sdk.init({
  processOnBackend: async () => {
		// Here you need to call your API to check the result of the liveness session
    return true;
  },
  onComplete: (result) => {
    console.log('Complete:', result);
  }
});

Parameters:

  • processOnBackend (function (auditImage?: Blob) => Promise<boolean>, optional): Async function executed to validate the result coming from your API if the session is valid It optionally receives an auditImage (Blob) and must return a boolean indicating whether the verification was approved or reproved.
  • onComplete (function, optional): Callback fired when verification completes

Returns: void


setTheme(theme)

Customize the UI theme colors and styles.

sdk.setTheme({
  accentColor: '#4F46E5',
  accentTextColor: '#FFFFFF',
  strokeWidth: 3,
  feedbackColor: '#10B981'
});

Parameters:

  • accentColor (string, optional): Primary UI color
  • accentTextColor (string, optional): Text color for accent elements
  • strokeWidth (number, optional): Width of detection overlay strokes
  • feedbackColor (string, optional): Color for feedback messages

Returns: void


Events

legitface-error

Fired when an error occurs during verification.

sdk.addEventListener('legitface-error', (event) => {
  console.error('Error:', event.detail);
  // event.detail.type: error type string
  // event.detail.severity: 'warning' | 'error' | 'fatal'
});

Event Detail:

{
  type: string;      // Error type (e.g., 'CAMERA_ACCESS_DENIED')
  severity: string;  // 'warning' | 'error' | 'fatal'
}

🔧 Configuration

Asset Path Auto-Detection

The SDK automatically detects where to load assets (ML models, WASM files) from the script tag's src attribute.

Important: Always include id="lf-sdk-script" on your script tag!

Development:

<script id="lf-sdk-script" src="/node_modules/legitface-sdk-web/dist/legitface-sdk.umd.js"></script>

→ Auto-detected path: /node_modules/legitface-sdk-web/dist/

Production (CDN):

<script id="lf-sdk-script" src="https://cdn.yoursite.com/sdk/legitface-sdk.umd.js"></script>

→ Auto-detected path: https://cdn.yoursite.com/sdk/

Production (Self-hosted):

<script id="lf-sdk-script" src="/static/sdk/legitface-sdk.umd.js"></script>

→ Auto-detected path: /static/sdk/

The SDK will automatically load:

  • Libraries from {auto-path}/lib/*.js
  • WASM files from {auto-path}/lib/*.wasm
  • Models from {auto-path}/lib/*.model

🚢 Deployment

Files to Deploy

Copy the entire dist/ folder from node_modules/legitface-sdk-web/:

your-app/
└── public/
    └── sdk/
        ├── legitface-sdk.umd.js     # Main SDK bundle
        ├── legitface-sdk.es.js      # ES module bundle
        ├── legitface-sdk.d.ts       # TypeScript definitions
        └── lib/                     # ML framework files + models
            ├── xxxxxxxx.min.js      # Framework libraries
            ├── mxxxxxxxx_cc.js      # WASM loaders
            ├── xxxxxxxx.wasm        # WebAssembly binaries
            └── xxxxxxxx.model       # ML models

Important: Deploy ALL files - the SDK loads them dynamically.


Server Configuration

HTTPS Required

Webcam access requires HTTPS in production:

server {
    listen 443 ssl;
    # SSL configuration...
}

CORS Headers

Allow cross-origin requests for WASM/model files:

location /sdk/ {
    add_header Access-Control-Allow-Origin *;
    add_header Cross-Origin-Opener-Policy same-origin;
    add_header Cross-Origin-Embedder-Policy require-corp;
}

MIME Types

Ensure proper MIME types for WASM:

types {
    application/wasm wasm;
}

Cache Control

Optimize caching for static assets:

location /sdk/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

🌐 Browser Support

BrowserMinimum VersionNotes
Chrome90+✅ Full support
Firefox88+✅ Full support
Safari14+✅ Full support
Edge90+✅ Full support
Opera76+✅ Full support
Samsung Internet14+✅ Mobile support

Requirements:

  • WebAssembly support
  • WebRTC/getUserMedia API
  • ES6+ JavaScript

📊 Performance

MetricValue
Initial Load~10 MB (on-demand)
SDK Bundle~157 KB (minified)
Cold Start~500-800ms
Detection Rate30 FPS
CPU Usage~10-15% (desktop)
Memory~50-80 MB

Optimization Tips:

  • Preload models on app init
  • Use loading="lazy" for video element
  • Consider service workers for caching
  • Enable gzip/brotli compression

🔒 Security & Privacy

On-Device Processing

All face detection and liveness checks happen entirely in the browser. No images or video frames are sent to external servers unless you explicitly implement it.

No External Dependencies

The SDK bundles all required ML models and frameworks - no external CDN calls or third-party tracking.

Content Security Policy

Add these directives to your CSP:

<meta http-equiv="Content-Security-Policy" 
      content="
        default-src 'self';
        script-src 'self' 'wasm-unsafe-eval';
        connect-src 'self' https://api.yourservice.com;
        img-src 'self' blob:;
        media-src 'self' blob:;
      ">

❓ Troubleshooting

Camera not accessible

Error: NotAllowedError or Permission denied

Solutions:

  • ✅ Ensure HTTPS is enabled (required for webcam)
  • ✅ Check browser permissions (camera access must be granted)
  • ✅ Verify no other app is using the camera

404 for SDK assets

Error: Failed to load /dist/lib/xxxxx.js

Solutions:

  • ✅ Ensure script tag has id="lf-sdk-script" for auto-detection
  • ✅ Verify the script src path is correct
  • ✅ Ensure all dist/ files (lib/, data/) are deployed
  • ✅ Check server CORS configuration
  • ✅ Check browser console for the detected path

WASM initialization failed

Error: RuntimeError: Aborted(CompileError: WebAssembly.instantiate())

Solutions:

  • ✅ Check MIME type for .wasm files (should be application/wasm)
  • ✅ Verify CORS headers allow WASM files
  • ✅ Ensure Cross-Origin-Embedder-Policy headers are set correctly

Models not loading

Error: Failed to load model

Solutions:

  • ✅ Check network tab for 404 errors on /lib/*.model files
  • ✅ Verify all model files are deployed in /lib/ directory
  • ✅ Ensure proper cache headers (not no-store)

Poor detection performance

Symptoms: Low FPS, laggy detection

Solutions:

  • ✅ Test on different device/browser
  • ✅ Reduce video resolution
  • ✅ Close other tabs/applications
  • ✅ Check browser GPU acceleration is enabled

📦 Package Contents

legitface-sdk-web/
├── dist/
│   ├── legitface-sdk.umd.js      # UMD bundle (browser)
│   ├── legitface-sdk.es.js       # ES module (bundlers)
│   ├── legitface-sdk.d.ts        # TypeScript definitions
│   └── lib/                      # All assets (libraries, WASM, models)
├── sdk/                          # Source files (reference only)
├── package.json
├── README.md
└── LICENSE

📄 License

Proprietary License - see LICENSE file for details.

This is proprietary software. You may not modify, reverse engineer, redistribute, or use it to create competing products. For licensing inquiries, contact: [email protected]