> For the complete documentation index, see [llms.txt](https://docs.accurascan.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.accurascan.com/language/web-plugin/face-plugin/svelte.md).

# Svelte

## Accura Face Plugin — Svelte Integration Guide

This guide walks you through integrating the **Accura Face Plugin** into a Svelte project built with Vite.

***

### Prerequisites

Before proceeding, ensure the following requirement is met:

* **`accura.xml`** — Place your `accura.xml` license file in the **`public/`** folder (Vite) or **`static/`** folder (SvelteKit) as `public/accura.xml` or `static/accura.xml` respectively. This file is required by the plugin to initialize the face detection engine. You can download it from here.

{% file src="/files/C1HSWtEDLSipZdnOKbNP" %}

***

### Step 1: Initialize Project

If you do not have an existing Svelte project, scaffold one using Vite:

```bash
npm create vite@latest my-face-app -- --template svelte
cd my-face-app
npm install
```

***

### Step 2: Install Plugin

Install the Accura Face Plugin package from the npm registry:

```bash
npm install accurafaceplugin
```

***

### Step 3: Implementation

Create a dedicated scanner component at `src/lib/FaceScanner.svelte`. The following snippet shows only the **plugin import and initialization** logic:

```svelte
<script>
  import { onMount, onDestroy } from 'svelte';

  let plugin = null; // Holds the active plugin instance for lifecycle management

  onMount(async () => {
    // Dynamically import the plugin inside onMount to guarantee browser-only execution.
    // Svelte's onMount lifecycle hook runs exclusively on the client side,
    // making it safe to access browser APIs such as the camera.
    const { default: FacePlugin } = await import('accurafaceplugin');

    // Instantiate the plugin with:
    //   1. The license file path (served from public/ or static/)
    //   2. The capture callback invoked on successful face detection
    //   3. A configuration object for UI and detection tuning
    plugin = new FacePlugin(
      "/accura.xml",   // Resolves to public/accura.xml (Vite) or static/accura.xml (SvelteKit)
      base64Handler,   // Fired automatically when the plugin captures a valid face
      {
        threshold: 3,       // Detection sensitivity (1–100; higher = stricter)
        textSize: "",       // Overlay text size (default if empty)
        textColor: "",      // Overlay text color (default if empty)
        textWeight: "",     // Overlay font weight (default if empty)
        textBgColor: "",    // Overlay background color (default if empty)
        BodyBgColor: "",    // Viewport background color (default if empty)
      }
    );

    // Activate the camera and begin the face detection session.
    await plugin.start();
  });

  // Release camera resources and destroy the plugin when the component is removed from the DOM.
  onDestroy(() => {
    if (plugin) {
      plugin.destroy();
    }
  });
</script>
```

***

### Step 4: Response Handling

When the plugin captures a valid face, it invokes the **`base64Handler`** callback with an object containing a `base64` property — a Data URL string representing the captured face image encoded in Base64 format (e.g., `data:image/jpeg;base64,/9j/...`).

**What is Base64?** Base64 is a binary-to-text encoding scheme that converts raw binary image data into a sequence of printable ASCII characters. The prefix segment (e.g., `data:image/jpeg;base64,`) conveys the MIME type, while the remainder is the encoded image payload. This format enables seamless transmission of binary content over text-based HTTP protocols without requiring binary transport mechanisms.

The following handler demonstrates forwarding the captured image to a remote verification endpoint:

```js
// Invoked automatically by the plugin upon each successful face capture event.
// Receives: { base64 } — a complete Data URL of the captured face image.
const base64Handler = async ({ base64 }) => {
    console.log("Base64 received:", base64);

    try {
        // Construct a multipart form payload for HTTP transmission.
        const formData = new FormData();

        // Attach the base64 string under the field key expected by your backend.
        formData.append("imagebase64", base64);

        // Dispatch the verification request to your server endpoint.
        // Replace the URL with your actual backend host and path.
        const response = await fetch("https://ip:port/upload.php", {
            method: "POST",
            body: formData,
        });

        // Parse the JSON response returned by the verification server.
        const data = await response.json();
        console.log("API Response:", data);

        // Read the liveness/match confidence score from the response payload.
        if (data && data.score !== undefined) {
            console.log(`Score: ${data.score}`);
        }
    } catch (error) {
        console.error("Error sending to API:", error);
    }
};
```

***

### Step 5: Demo Implementation

The following is the **complete, production-ready component**. Copy and paste it directly into `src/lib/FaceScanner.svelte`. The original logic is preserved exactly as-is.

```svelte
<script>
  import { onMount, onDestroy } from 'svelte';
  
  let container;
  let plugin = null;
  let isReady = false;

  onMount(async () => {
    try {
      // Dynamic import for client-side only execution
      const { default: FacePlugin } = await import('accurafaceplugin');

      const base64Handler = async ({ base64 }) => {
        console.log("Base64 received:", base64);

        try {
            const formData = new FormData();
            formData.append("imagebase64", base64);

            const response = await fetch(
                "https://ip:port/upload.php",
                {
                    method: "POST",
                    body: formData,
                },
            );

            const data = await response.json();
            console.log("API Response:", data);

            // Display the score on UI
            if (data && data.score !== undefined) {
                console.log(`Score: ${data.score}`);
            }
        } catch (error) {
            console.error("Error sending to API:", error);
        }
    };
      
      plugin = new FacePlugin(
        "/accura.xml",
        base64Handler,
        {
        threshold: 3,
        textSize: "",
        textColor: "",
        textWeight: "",
        textBgColor: "",
        BodyBgColor: "",
      }
      );
      
      await plugin.start();
      isReady = true;
    } catch (error) {
      console.error("Svelte Plugin Error:", error);
    }
  });

  onDestroy(() => {
    if (plugin) {
      plugin.destroy();
    }
  });
</script>
```

***

### Step 6: Usage

Import and render the component in `App.svelte`:

```svelte
<script>
  import FaceScanner from './lib/FaceScanner.svelte';
</script>

<FaceScanner />
```

***

### Step 7: Running the Project

```bash
npm run dev
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.accurascan.com/language/web-plugin/face-plugin/svelte.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
