Mixpanel (JavaScript) — Basic Setup Tutorial
Install
npm install mixpanel-browser
Create a tiny helper — src/mixpanel.js
import mixpanel from "mixpanel-browser";
// Initialize Mixpanel with your project token
// Prefer an env var injected at build time (recommended):
// mixpanel.init(import.meta.env.VITE_MIXPANEL_TOKEN);
mixpanel.init("YOUR_PROJECT_TOKEN_HERE");
// Track a page view
export const trackPageView = (page) => {
mixpanel.track("Page View", { page });
};
// Track a custom event
export const trackEvent = (event, properties = {}) => {
mixpanel.track(event, properties);
};
// Identify a user (call on login/signup)
export const identifyUser = (userId) => {
mixpanel.identify(userId);
};
export { default } from "mixpanel-browser";
Use it in Svelte/SvelteKit — basic page view
<script>
import { onMount } from "svelte";
import { trackPageView } from "../mixpanel"; // adjust the path as needed
onMount(() => {
trackPageView(globalThis.location.pathname);
});
</script>
Track a custom event (example)
import { trackEvent } from "../mixpanel";
function onSignup(plan) {
trackEvent("Signed Up", { plan, source: "landing" });
}
Identify the user after login/signup
import { identifyUser } from "../mixpanel";
// After the server confirms login:
identifyUser(user.id);
Tips
- Use separate Mixpanel projects/tokens for dev and prod.
- Keep PII out of event properties; set email/name on the user profile only if needed.
- For EU/IN data residency, init with `api_host: 'https://api-eu.mixpanel.com'` or `'https://api-in.mixpanel.com'`.
Taylor Swift
“I’ve got a blank space, baby.”
Comments
Post a Comment