Vue.js SDK
Vue 3 composables and plugin for seamless integration in Vue.js applications
Installation
npm (Recommended)
Install the Vue SDK using npm, the Node.js package manager. This is the recommended installation method for most Vue projects.
npm install @keverdjs/fraud-sdk-vueyarn
Alternatively, install using Yarn if you prefer it over npm.
yarn add @keverdjs/fraud-sdk-vuePeer Dependencies
The Vue SDK requires Vue 3.0 or higher (for Composition API support). Vue should already be installed in your project, but if not, install it:
npm install vue@^3.0.0
# or
yarn add vue@^3.0.0Note: The SDK uses Vue 3's Composition API (composables, refs, provide/inject) internally, so Vue 3.0+ is required. The SDK is compatible with both Options API and Composition API components, but composables can only be used in Composition API components.
Quick Start
1. Setup Provider or Install Plugin
You can use the SDK in two ways: install it as a Vue plugin (recommended for global access) or use the useKeverdProvider composable in your root component.
Important: The endpoint must use HTTPS. The SDK will throw an error if you provide an HTTP URL. The default API endpoint is https://api.keverd.com.
Option A - Plugin Installation (Recommended): Install the SDK as a Vue plugin for global access across all components.
import { createApp } from 'vue';
import App from './App.vue';
import KeverdPlugin from '@keverdjs/fraud-sdk-vue';
const app = createApp(App);
app.use(KeverdPlugin, {
apiKey: process.env.VUE_APP_KEVERD_API_KEY, // Use environment variables
endpoint: 'https://api.keverd.com', // Optional: defaults to https://api.keverd.com
debug: process.env.NODE_ENV === 'development', // Enable debug in dev only
});
app.mount('#app');Option B - Composable Setup: Use the useKeverdProvider composable in your root component.
<script setup>
import { useKeverdProvider } from '@keverdjs/fraud-sdk-vue';
// Setup provider (call once in root component, e.g., App.vue)
useKeverdProvider({
apiKey: import.meta.env.VITE_KEVERD_API_KEY,
endpoint: 'https://api.keverd.com',
debug: import.meta.env.DEV
});
</script>Dependency Injection: The SDK uses Vue's provide/inject API to share the SDK instance with all child components. This ensures the SDK is initialized once and shared across your entire application.
Reactive State: The SDK instance and ready state are provided as Vue refs, making them reactive. Components can reactively respond to SDK state changes.
2. Use Composable in Components
The useKeverdVisitorData composable provides a Vue-friendly interface for accessing visitor data and risk assessment. The composable manages loading states, error handling, and data fetching automatically using Vue's reactivity system.
Performance: Data collection typically completes in under 50ms. The total time (including network request) is typically under 200ms (p99 latency). The composable uses Vue's reactivity system to prevent unnecessary re-renders.
<script setup>
import { useKeverdVisitorData } from '@keverdjs/fraud-sdk-vue';
// Use composable in any component
const { data, loading, error, getData } = useKeverdVisitorData({
extendedResult: true, // Include extended result data
immediate: true, // Automatically fetch data on mount
});
// Handle risk score reactively
const riskLevel = computed(() => {
if (!data.value) return 'unknown';
if (data.value.riskScore >= 70) return 'high';
if (data.value.riskScore >= 30) return 'medium';
return 'low';
});
</script>
<template>
<div>
<!-- Loading state -->
<div v-if="loading">Loading risk assessment...</div>
<!-- Error state -->
<div v-else-if="error">
<p>Error: {{ error.message }}</p>
<button @click="getData">Retry</button>
</div>
<!-- Success state -->
<div v-else-if="data">
<p>Risk Score: {{ data.riskScore }}/100</p>
<p>Action: {{ data.action }}</p>
<p>Reasons: {{ data.reasons.join(', ') }}</p>
<p>Risk Level: {{ riskLevel }}</p>
<button @click="getData">Reload data</button>
</div>
<!-- No data state -->
<div v-else>
<button @click="getData">Check Risk</button>
</div>
</div>
</template>API Reference
useKeverdProvider
Composable that sets up the Keverd SDK provider using Vue's dependency injection system. This composable initializes the SDK and provides it to all child components via Vue's provide/inject API. Call this composable once in your root component (e.g., App.vue) or app setup.
useKeverdProvider(options: KeverdLoadOptions)
Composable that initializes the SDK and provides it to child components via dependency injection.
Parameters:
options(KeverdLoadOptions): Configuration object for SDK initialization. SeeKeverdLoadOptionsbelow for details.
Returns: void
Dependency Injection: The composable uses Vue's provide API to inject the SDK instance and ready state into the component tree. Child components can access these via useKeverdContext or useKeverdVisitorData.
Reactive State: The SDK instance and ready state are provided as Vue refs, making them reactive. Components can reactively respond to SDK state changes.
KeverdLoadOptions
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
| apiKey | string | Yes | — | API key for authenticating requests to the Keverd API. Obtain your API key from the API Keys page in the dashboard. Keep your API key secure and never commit it to version control. Use environment variables in production. |
| endpoint | string | No | 'https://api.keverd.com' | Base URL for the fingerprint API endpoint. Must start with "https://" (HTTP is not allowed for security). Only change this if you're using a custom endpoint or testing environment. |
| debug | boolean | No | false | Enable debug logging. When true, the SDK will log debug information to the browser console. Set to true during development and false in production. |
useKeverdVisitorData
Vue composable for accessing visitor data and risk assessment. This composable provides a Vue-friendly interface that manages loading states, error handling, and data fetching automatically using Vue's reactivity system. The composable must be used within a component that has access to the SDK via useKeverdProvider or the Vue plugin.
useKeverdVisitorData(options?: KeverdVisitorDataHookOptions)
Composable that returns reactive visitor data, loading state, error state, and a function to manually fetch data.
Parameters:
options(optional): Hook configuration object- -
extendedResult(boolean, optional): Include extended result data in the response. Default:false - -
immediate(boolean, optional): Automatically fetch data when the component mounts. Default:false - -
ignoreCache(boolean, optional): Ignore cached results and force a fresh API call. Default:false
Returns: KeverdVisitorDataResult object containing:
data(Ref<KeverdVisitorData | null>): Reactive visitor data. This is a Vue ref that updates automatically when data is fetched.loading(Ref<boolean>): Reactive loading state. This istrueduring the initial fetch and whengetDatais called.error(Ref<KeverdError | null>): Reactive error state. This isnullwhen there's no error.getData(function): Function to manually fetch data. Returns a Promise that resolves when data is fetched. Can throw errors if the request fails.
Reactivity: All returned values are Vue refs, making them reactive. Components will automatically re-render when these values change. Use .value to access the underlying values in JavaScript, or use them directly in templates.
Performance: The composable uses Vue's reactivity system to prevent unnecessary re-renders. Data collection typically completes in under 50ms, and the total time (including network request) is typically under 200ms (p99 latency).
Error Handling: Errors are automatically caught and stored in the error ref. The composable will not throw errors, so you can safely use it without try-catch blocks. However, the getData function can throw errors if called manually.
Usage Example
const { data, loading, error, getData } = useKeverdVisitorData({
extendedResult: true,
immediate: true
});
// Manual fetch
await getData();useKeverdContext
Composable to access the Keverd SDK instance directly from Vue's dependency injection system. This composable provides direct access to the SDK instance and the ready state, allowing you to call SDK methods directly if needed. The composable must be used within a component that has access to the SDK via useKeverdProvider or the Vue plugin.
useKeverdContext()
Composable that returns the SDK instance and ready state from Vue's dependency injection system. Returns an object with sdk: Ref<KeverdSDK | null> and isReady: Ref<boolean>.
Parameters: None
Returns: Object containing:
sdk(Ref<KeverdSDK | null>): The SDK instance as a Vue ref. Usesdk.valueto access the SDK instance and call methods directly (e.g.,sdk.value.getVisitorData()).isReady(Ref<boolean>): Whether the SDK is initialized and ready to use. This istrueafter the provider has initialized the SDK. UseisReady.valueto check the ready state.
Throws: Throws an error if called outside of a component that has access to the SDK (i.e., if useKeverdProvider was not called or the plugin was not installed).
const { sdk, isReady } = useKeverdContext();
if (isReady.value && sdk.value) {
const data = await sdk.value.getVisitorData();
// Custom logic with direct SDK access
}KeverdVisitorData
The visitor data object returned by the SDK. This object contains the risk assessment, action recommendation, and session information. When returned from useKeverdVisitorData, this object is wrapped in a Vue ref for reactivity.
KeverdVisitorData Interface
interface KeverdVisitorData {
visitorId: string; // Unique visitor identifier (UUID)
riskScore: number; // Risk score (0-100, where 100 is highest risk)
score: number; // Risk score as float (0.0-1.0, normalized)
action: 'allow' | 'soft_challenge' | 'hard_challenge' | 'block';
reasons: string[]; // Array of risk reasons
sessionId: string; // Session identifier (UUID)
requestId: string; // Request identifier (UUID, same as sessionId)
simSwapEngine?: { // SIM swap detection results (null for web SDKs)
risk: number;
flags: {
sim_changed?: boolean;
device_changed?: boolean;
behavior_anomaly?: boolean;
time_anomaly?: boolean;
velocity_anomaly?: boolean;
};
};
confidence?: number; // Confidence score (inverse of risk, 0.0-1.0)
}visitorId: Unique visitor identifier in UUID format. This identifier is consistent across sessions for the same device/browser.
riskScore: Risk score as an integer from 0 (lowest risk) to 100 (highest risk). Use this score to make security decisions in your application.
score: Normalized risk score as a float between 0.0 (lowest risk) and 1.0 (highest risk). This is equal to riskScore / 100.
action: Recommended action based on the risk score. Possible values: 'allow', 'soft_challenge', 'hard_challenge', or 'block'.
reasons: Array of strings explaining why the risk score was assigned. Each string describes a specific risk factor.
sessionId: Unique session identifier in UUID format. This identifier is generated client-side and is consistent across requests within the same browser session.
requestId: Unique request identifier in UUID format. This is the same as sessionId and is included for backward compatibility.
simSwapEngine: SIM swap detection data. This field is always null or undefined for web SDKs, as SIM card information is only available on mobile devices.
confidence: Confidence score as a float between 0.0 and 1.0. This is the inverse of the risk score (confidence = 1.0 - score). Higher values indicate higher confidence in the assessment.
Data Collection
The Vue SDK collects the same types of data as the Vanilla JavaScript SDK: device information, session information, and behavioral data. All sensitive identifiers are hashed client-side before transmission to ensure privacy and compliance with data protection regulations. No personally identifiable information (PII) is collected or transmitted in plain text.
Device Information
Collected automatically by the SDK. Includes device fingerprint, screen dimensions, timezone, locale, and hardware information. All sensitive data is hashed using SHA-256 before transmission.
Session Information
Tracks session and installation data. Session data is persisted in localStorage and is consistent across page reloads within the same browser session.
Behavioral Data
Collected passively as users interact with your application. The collector tracks mouse movements, keyboard input, touch gestures, and scroll events. Data collection starts automatically when the SDK is initialized and stops when the provider unmounts.
Privacy: Behavioral data is aggregated and anonymized. Individual keystrokes or mouse movements are not transmitted; only statistical summaries are sent to the API.
Hashing and Privacy
All sensitive identifiers are hashed using SHA-256 before transmission. The SDK handles all hashing operations internally. This approach ensures compliance with GDPR, CCPA, and other data protection regulations.
Complete Example
Here's a complete example showing how to integrate the Vue SDK into a Vue 3 application. This example demonstrates provider setup, composable usage, risk assessment, and error handling.
<script setup>
import { ref } from 'vue';
import { useKeverdProvider, useKeverdVisitorData } from '@keverdjs/fraud-sdk-vue';
// Setup provider (in root component)
useKeverdProvider({
apiKey: 'your-api-key-here',
endpoint: 'https://api.keverd.com',
debug: false
});
// Use composable
const { data, loading, error, getData } = useKeverdVisitorData({
extendedResult: true,
immediate: true
});
const handleRiskCheck = async () => {
try {
await getData();
} catch (err) {
console.error('Failed to get visitor data:', err);
}
};
const getRiskLevel = () => {
if (!data.value) return 'unknown';
if (data.value.riskScore >= 70) return 'high';
if (data.value.riskScore >= 30) return 'medium';
return 'low';
};
</script>
<template>
<div>
<h1>Risk Assessment</h1>
<div v-if="loading">Loading risk assessment...</div>
<div v-else-if="error">
<p>Error: {{ error.message }}</p>
<button @click="handleRiskCheck">Retry</button>
</div>
<div v-else-if="data">
<p>Risk Score: {{ data.riskScore }}/100</p>
<p>Action: {{ data.action }}</p>
<p>Reasons: {{ data.reasons.join(', ') }}</p>
<p>Risk Level: {{ getRiskLevel() }}</p>
<button @click="handleRiskCheck">Refresh</button>
</div>
<div v-else>
<button @click="handleRiskCheck">Check Risk</button>
</div>
</div>
</template>Plugin Installation
You can install the SDK as a Vue plugin for global access across all components. This is the recommended approach if you want to use the SDK throughout your entire application without calling useKeverdProvider in each component.
You can also install the SDK as a Vue plugin for global access:
import { createApp } from 'vue';
import App from './App.vue';
import KeverdPlugin from '@keverdjs/fraud-sdk-vue';
const app = createApp(App);
app.use(KeverdPlugin, {
apiKey: 'your-api-key-here',
endpoint: 'https://api.keverd.com',
debug: false
});
app.mount('#app');After installing the plugin, you can use useKeverdVisitorData and useKeverdContext in any component without calling useKeverdProvider.
Error Handling
The Vue SDK handles errors gracefully and provides them through the reactive error ref in the useKeverdVisitorData composable. Here's how to handle different error scenarios:
Network Errors
Network errors occur when the device cannot connect to the API or when the request times out. The SDK uses 30-second timeouts for connection, read, and write operations.
<script setup>
import { watch } from 'vue';
import { useKeverdVisitorData } from '@keverdjs/fraud-sdk-vue';
const { data, loading, error, getData } = useKeverdVisitorData({
immediate: true,
});
watch(error, (err) => {
if (err) {
if (err.message.includes('timeout') || err.message.includes('Timeout')) {
// Handle timeout - retry with exponential backoff
console.warn('Request timed out, retrying...');
setTimeout(() => getData(), 1000);
} else if (err.message.includes('network') || err.message.includes('Network')) {
// Handle network connectivity issues
console.error('Network error:', err.message);
showNetworkError();
}
}
});
</script>API Errors
API errors occur when the server returns an error status code (4xx or 5xx). Common causes include invalid API keys, rate limiting, or server errors.
watch(error, (err) => {
if (err) {
if (err.message.includes('401') || err.message.includes('Unauthorized')) {
// Invalid API key
console.error('Invalid API key. Please check your configuration.');
showConfigurationError();
} else if (err.message.includes('429') || err.message.includes('rate limit')) {
// Rate limit exceeded
console.warn('Rate limit exceeded. Please retry after some time.');
showRateLimitError();
} else if (err.message.includes('500') || err.message.includes('502') || err.message.includes('503')) {
// Server errors - retry with backoff
console.error('Server error:', err.message);
retryWithBackoff();
}
}
});SDK Not Ready Errors
These errors occur when you try to use the SDK before it's initialized or when the provider hasn't mounted yet.
watch(error, (err) => {
if (err && err.code === 'SDK_NOT_READY') {
// SDK not initialized - wait a bit and retry
console.warn('SDK not ready, retrying...');
setTimeout(() => getData(), 100);
}
});Best Practices for Error Handling
- Use watch to monitor errors: Set up a
watchto monitor theerrorref and handle errors appropriately. - Implement retry logic: For transient errors (network timeouts, server errors), implement retry logic with exponential backoff.
- Fail gracefully: Decide on a fail-open or fail-closed strategy. Fail-open allows access when the SDK fails, while fail-closed blocks access. Choose based on your security requirements.
- Log errors: Log errors to your error tracking service (e.g., Sentry, LogRocket) for debugging and monitoring.
- User feedback: Provide clear feedback to users when errors occur, especially for authentication or security-related failures.
Best Practices
Follow these best practices to ensure optimal performance, security, and user experience when integrating the Vue SDK:
Provider Setup
- Call provider once: Call
useKeverdProvideronce in your root component (e.g.,App.vue) or install the plugin globally in your app setup. - Use environment variables: Store your API key in environment variables and never commit it to version control. Use different API keys for development, staging, and production environments.
- Enable debug in development only: Set
debug: trueonly in development environments. Disable it in production to avoid exposing sensitive information in the console.
Composable Usage
- Use immediate option wisely: Set
immediate: trueonly when you need data immediately on component mount. For on-demand fetching, useimmediate: falseand callgetData()manually. - Avoid excessive calls: Don't call
getData()on every render or user interaction. Use it strategically for high-value or high-risk operations. - Handle loading and error states: Always handle the
loadinganderrorrefs in your components to provide good user experience. - Use computed properties: Use Vue's
computedto derive values from the data ref for better performance and reactivity.
Security
- Protect your API key: Never expose your API key in client-side code that can be viewed in the browser. Use environment variables or a secure configuration management system.
- Use HTTPS: Always use HTTPS endpoints. The SDK will not work with HTTP endpoints for security reasons.
- Validate risk scores: Don't blindly trust risk scores. Use them as one factor in your security decision-making process, along with other signals.
- Monitor for anomalies: Set up monitoring and alerting for unusual patterns in risk scores or error rates.
Performance
- Non-blocking: The SDK is designed to be non-blocking. Data collection and API calls happen asynchronously and won't block your UI.
- Minimal impact: Behavioral data collection is passive and has minimal impact on page performance. The SDK uses efficient event listeners that are automatically cleaned up.
- Bundle size: The SDK is lightweight and has a small bundle size. It won't significantly impact your application's load time.
Privacy and Compliance
- GDPR compliance: The SDK is designed to be GDPR-compliant. All sensitive data is hashed client-side, and no PII is collected or transmitted.
- User consent: Consider obtaining user consent before initializing the SDK, especially in regions with strict privacy regulations.
- Privacy policy: Update your privacy policy to inform users about data collection and how it's used for fraud detection.
Risk Score Interpretation
| Score Range | Action | Meaning |
|---|---|---|
| 0-29 | allow | Low risk, proceed with login |
| 30-69 | soft_challenge or hard_challenge | Moderate risk, require MFA |
| 70-100 | block | High risk, deny access |
Features
Vue 3 Composables
Reactive composables using Vue 3 Composition API
Plugin System
Easy global installation with Vue plugin
TypeScript Support
Full type definitions included
Reactive Data
All data is reactive using Vue refs
Requirements
- Vue 3.0 or higher
- Modern browser with ES2020 support