Skip to content

Vite/Vue Integration

Integrate usertrax with your Vite/Vue application to track conversions and user interactions.

  1. Add Script to HTML

    Add the usertrax script directly to your index.html file:

    index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Your App</title>
    <!-- usertrax tracking script -->
    <script
    src="https://usertrax.io/cvs.js"
    data-key="YOUR_PUBLIC_KEY"
    ></script>
    </head>
    <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
    </body>
    </html>
  2. Add Environment Variable

    Create or update your .env file:

    VITE_USERTRAX_KEY=your_public_key_here
  3. Create Helper Functions

    Create a new file src/lib/usertrax.js in your project:

    src/lib/usertrax.js
    const USERTRAX_CONFIG = {
    publicKey: import.meta.env.VITE_USERTRAX_KEY,
    };
    // Helper functions for common events
    export const trackConversion = (data) => {
    if (window.usertrax) {
    window.usertrax.push(data);
    } else {
    console.warn("Usertrax not loaded yet");
    }
    };
    export const trackPageView = (page) => {
    if (window.usertrax) {
    window.usertrax.push({
    event: "page_view",
    page: page,
    });
    } else {
    console.warn("Usertrax not loaded yet");
    }
    };
    export const trackEvent = (eventName, data = {}) => {
    if (window.usertrax) {
    window.usertrax.push({
    event: eventName,
    ...data,
    });
    } else {
    console.warn("Usertrax not loaded yet");
    }
    };
  4. Create Vue Composable

    Create a composable for easier tracking in components:

    src/composables/useUsertrax.js
    import { ref, onMounted } from "vue";
    import { trackConversion, trackEvent } from "../lib/usertrax";
    export function useUsertrax() {
    const isReady = ref(false);
    onMounted(() => {
    // Check if usertrax is loaded
    const checkUsertrax = () => {
    if (window.usertrax) {
    isReady.value = true;
    } else {
    setTimeout(checkUsertrax, 100);
    }
    };
    checkUsertrax();
    });
    const trackConversionEvent = (data) => {
    if (isReady.value) {
    trackConversion(data);
    } else {
    console.warn("Usertrax not ready yet");
    }
    };
    const trackCustomEvent = (eventName, data = {}) => {
    if (isReady.value) {
    trackEvent(eventName, data);
    } else {
    console.warn("Usertrax not ready yet");
    }
    };
    const trackFormSubmission = (formData) => {
    trackCustomEvent("form_submitted", formData);
    };
    const trackButtonClick = (buttonData) => {
    trackCustomEvent("button_clicked", buttonData);
    };
    return {
    isReady,
    trackConversion: trackConversionEvent,
    trackEvent: trackCustomEvent,
    trackFormSubmission,
    trackButtonClick,
    };
    }
  5. Setup Router Integration

    Update your router to track page views:

    src/router/index.js
    import { createRouter, createWebHistory } from "vue-router";
    import { trackPageView } from "../lib/usertrax";
    const routes = [
    {
    path: "/",
    name: "Home",
    component: () => import("../views/Home.vue"),
    },
    {
    path: "/about",
    name: "About",
    component: () => import("../views/About.vue"),
    },
    // ... other routes
    ];
    const router = createRouter({
    history: createWebHistory(),
    routes,
    });
    // Track page views
    router.afterEach((to) => {
    trackPageView(to.path);
    });
    export default router;
src/components/CheckoutForm.vue
<template>
<form @submit="handlePurchase">
<input v-model="form.email" type="email" placeholder="Email" required />
<input
v-model="form.firstName"
type="text"
placeholder="First Name"
required
/>
<input
v-model="form.lastName"
type="text"
placeholder="Last Name"
required
/>
<input v-model="form.total" type="number" placeholder="Total" required />
<button type="submit">Complete Purchase</button>
</form>
</template>
<script setup>
import { ref } from "vue";
import { useUsertrax } from "../composables/useUsertrax";
const { trackConversion } = useUsertrax();
const form = ref({
email: "",
firstName: "",
lastName: "",
total: 0,
});
const handlePurchase = async (e) => {
e.preventDefault();
try {
// Process purchase
const response = await fetch("/api/checkout", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(form.value),
});
if (response.ok) {
// Track conversion
trackConversion({
event: "purchase",
id: `order_${Date.now()}`,
total: parseFloat(form.value.total),
currency: "EUR",
user_data: {
email: form.value.email,
firstname: form.value.firstName,
lastname: form.value.lastName,
},
metadata: {
payment_method: "credit_card",
},
});
}
} catch (error) {
console.error("Checkout error:", error);
}
};
</script>
src/components/ContactForm.vue
<template>
<form @submit="handleSubmit">
<input v-model="form.name" type="text" placeholder="Name" required />
<input v-model="form.email" type="email" placeholder="Email" required />
<textarea v-model="form.message" placeholder="Message" required></textarea>
<button type="submit">Send Message</button>
</form>
</template>
<script setup>
import { ref } from "vue";
import { useUsertrax } from "../composables/useUsertrax";
const { trackFormSubmission } = useUsertrax();
const form = ref({
name: "",
email: "",
message: "",
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
// Submit form
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(form.value),
});
if (response.ok) {
// Track form submission
trackFormSubmission({
form_type: "contact",
form_data: {
name: form.value.name,
email: form.value.email,
message_length: form.value.message.length,
},
});
}
} catch (error) {
console.error("Form submission error:", error);
}
};
</script>
src/components/CTAButton.vue
<template>
<button @click="handleClick" :class="variant">
<slot />
</button>
</template>
<script setup>
import { useUsertrax } from "../composables/useUsertrax";
const { trackButtonClick } = useUsertrax();
const props = defineProps({
variant: {
type: String,
default: "primary",
},
});
const handleClick = () => {
trackButtonClick({
button_text: "CTA Button",
button_variant: props.variant,
page: window.location.pathname,
});
};
</script>
src/components/ProductCard.vue
<template>
<div class="product-card">
<img :src="product.image" :alt="product.name" />
<h3>{{ product.name }}</h3>
<p>{{ product.price }}€</p>
<button @click="addToCart">Add to Cart</button>
</div>
</template>
<script setup>
import { useUsertrax } from "../composables/useUsertrax";
const { trackEvent } = useUsertrax();
const props = defineProps({
product: {
type: Object,
required: true,
},
});
const addToCart = () => {
trackEvent("product_added_to_cart", {
product_id: props.product.id,
product_name: props.product.name,
product_price: props.product.price,
product_category: props.product.category,
});
};
</script>

Create a Vue plugin for global usertrax access:

src/plugins/usertrax.js
import { initUsertrax } from "../lib/usertrax";
export default {
install: (app) => {
// Initialize usertrax
initUsertrax();
// Add global properties
app.config.globalProperties.$usertrax = {
trackConversion: (data) => {
if (window.usertrax) {
window.usertrax.push(data);
}
},
trackEvent: (eventName, data = {}) => {
if (window.usertrax) {
window.usertrax.push({
event: eventName,
...data,
});
}
},
};
},
};
src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import usertraxPlugin from "./plugins/usertrax";
const app = createApp(App);
app.use(router);
app.use(usertraxPlugin);
app.mount("#app");
src/stores/analytics.js
import { defineStore } from "pinia";
import { trackEvent } from "../lib/usertrax";
export const useAnalyticsStore = defineStore("analytics", {
state: () => ({
events: [],
}),
actions: {
trackUserAction(action, data = {}) {
const event = {
action,
timestamp: new Date().toISOString(),
...data,
};
this.events.push(event);
trackEvent("user_action", event);
},
trackPurchase(order) {
trackEvent("purchase", {
order_id: order.id,
total: order.total,
currency: order.currency,
items: order.items,
});
},
trackPageView(page) {
trackEvent("page_view", { page });
},
},
});
src/directives/usertrax.js
import { trackEvent } from "../lib/usertrax";
export const usertraxClick = {
mounted(el, binding) {
el.addEventListener("click", () => {
const eventName = binding.arg || "element_clicked";
const data = binding.value || {};
trackEvent(eventName, {
element: el.tagName.toLowerCase(),
element_id: el.id,
element_class: el.className,
...data,
});
});
},
};
<!-- Usage in components -->
<template>
<button v-usertrax-click:button_clicked="{ button_type: 'cta' }">
Click me
</button>
</template>
  • Events not being sent: Check browser console for errors and verify API key
  • Environment variables not working: Ensure variables are prefixed with VITE_
  • Script not loading: Check network tab for script loading errors
  • Vue 3 compatibility: Make sure you’re using Vue 3 composition API
src/types/usertrax.d.ts
declare global {
interface Window {
usertrax: {
push: (data: any) => void;
};
}
}
export interface UsertraxConfig {
publicKey: string;
scriptUrl?: string;
debug?: boolean;
}
export interface ConversionData {
id?: string;
value?: number;
currency?: string;
user_data?: Record<string, any>;
metadata?: Record<string, any>;
}
export interface UsertraxEvent {
event: string;
[key: string]: any;
}