@lostkode/analytics
v1.0.0
Published
Privacy-focused, GDPR-compliant analytics tracking for LostKode client projects
Maintainers
Readme
@lostkode/analytics
Privacy-focused, GDPR-compliant analytics tracking for LostKode client projects.
Features
- 🔒 Privacy-First: No cookies, no personal data, no IP addresses
- ✅ GDPR Compliant: Respects DNT (Do Not Track) browser setting
- 🚀 Easy Integration: Simple API for tracking page views and events
- ⚡ Lightweight: Minimal bundle size
- 🎯 TypeScript: Full TypeScript support with type definitions
- ⚛️ React Support: Built-in React components and hooks
Installation
npm install @lostkode/analyticsor
yarn add @lostkode/analyticsQuick Start
Vanilla JavaScript
import { init } from '@lostkode/analytics';
// Initialize with your API key
const analytics = init({
apiKey: 'your-api-key-here'
});
// Track page views
analytics.trackPageView();
// Track custom events
analytics.trackEvent({
eventName: 'button_clicked',
eventData: { button: 'signup', plan: 'pro' }
});React
import { AnalyticsProvider } from '@lostkode/analytics/react';
function App() {
return (
<AnalyticsProvider apiKey="your-api-key-here">
<YourApp />
</AnalyticsProvider>
);
}React with Hook
import { useAnalytics } from '@lostkode/analytics/react';
function MyComponent() {
const analytics = useAnalytics({ apiKey: 'your-api-key-here' });
const handleClick = () => {
analytics.trackEvent({
eventName: 'button_clicked',
eventData: { button: 'cta' }
});
};
return <button onClick={handleClick}>Click Me</button>;
}API Reference
init(config)
Initialize the analytics tracker.
Parameters:
config.apiKey(string, required): Your LostKode Analytics API keyconfig.apiEndpoint(string, optional): Custom API endpoint (defaults tohttps://lostkode.com/api/analytics/track)config.respectDNT(boolean, optional): Respect Do Not Track browser setting (defaults totrue)config.consentGiven(boolean, optional): User consent for city-level tracking (defaults tofalse)
Returns: Analytics instance with trackPageView and trackEvent methods
trackPageView(path?)
Track a page view.
Parameters:
path(string, optional): Custom path to track (defaults to current URL path)
trackEvent(options)
Track a custom event.
Parameters:
options.eventName(string, required): Name of the eventoptions.eventData(object, optional): Additional event data
Consent Management (Optional)
If your project is configured to track city-level geographic data, you must obtain user consent for GDPR compliance.
Using the ConsentPopup Component
import { useState, useEffect } from 'react';
import { AnalyticsProvider } from '@lostkode/analytics/react';
import { ConsentPopup } from '@lostkode/analytics/consent';
function App() {
const [showConsent, setShowConsent] = useState(false);
const [consentGiven, setConsentGiven] = useState(false);
useEffect(() => {
// Check if consent was already given
const consent = localStorage.getItem('_lk_consent_your-api-key');
if (!consent) {
setShowConsent(true);
} else {
setConsentGiven(consent === 'accepted');
}
}, []);
const handleConsent = (accepted: boolean) => {
setConsentGiven(accepted);
setShowConsent(false);
};
return (
<>
{showConsent && (
<ConsentPopup
apiKey="your-api-key"
onConsent={handleConsent}
customStyles={{
backgroundColor: '#ffffff',
textColor: '#000000',
buttonAcceptColor: '#10b981',
buttonDeclineColor: '#ef4444',
fontFamily: 'Arial, sans-serif'
}}
position="bottom"
message="We use analytics to improve your experience. This includes tracking your approximate location. Learn more in our privacy policy."
/>
)}
<AnalyticsProvider
apiKey="your-api-key"
consentGiven={consentGiven}
>
<YourApp />
</AnalyticsProvider>
</>
);
}Custom Consent Implementation
You can also implement your own consent mechanism:
import { AnalyticsProvider } from '@lostkode/analytics/react';
function App() {
const [consentGiven, setConsentGiven] = useState(false);
// Your custom consent logic
const handleCustomConsent = () => {
setConsentGiven(true);
localStorage.setItem('my-consent', 'true');
};
return (
<AnalyticsProvider
apiKey="your-api-key"
consentGiven={consentGiven}
>
<YourApp />
</AnalyticsProvider>
);
}Privacy Policy Notice
Important: When using city-level tracking, you must inform users in your privacy policy. Add text similar to:
We use LostKode Analytics to understand how visitors use our website. With your consent, we collect your approximate location (city-level) to provide better localized experiences. This data is anonymized and cannot be used to identify you personally. You can withdraw consent at any time.
Configuration
Getting Your API Key
- Log in to your LostKode dashboard at https://lostkode.com/dashboard
- Navigate to your project settings
- Find your Analytics API Key in the Analytics section
- Copy the key and add it to your environment variables
Environment Variables
We recommend storing your API key in environment variables:
# .env
NEXT_PUBLIC_LOSTKODE_API_KEY=your-api-key-hereThen use it in your code:
const analytics = init({
apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY
});Privacy & GDPR Compliance
This package is designed to be GDPR-compliant by default:
- No Cookies: Uses sessionStorage for anonymous session tracking
- No Personal Data: Doesn't collect any personally identifiable information
- No IP Addresses: IP addresses are not stored
- Country-Level Geo by Default: Geographic data is limited to country level by default
- Optional Region/City Tracking: Can be enabled with proper user consent
- DNT Support: Respects Do Not Track browser settings
- Anonymous Sessions: Session IDs are cryptographically random and cannot be linked to individuals
What Data is Collected?
The following anonymous data is collected:
- Page paths visited
- Referrer URLs
- Browser type (e.g., Chrome, Firefox)
- Operating system (e.g., Windows, macOS)
- Device type (desktop, mobile, tablet)
- Country (country-level only, no precise location)
- Custom event names and data (if you use
trackEvent)
Integration Examples
Next.js
// app/layout.tsx
import { AnalyticsProvider } from '@lostkode/analytics/react';
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<AnalyticsProvider
apiKey={process.env.NEXT_PUBLIC_LOSTKODE_API_KEY!}
autoTrack={true}
>
{children}
</AnalyticsProvider>
</body>
</html>
);
}Tracking Form Submissions
function ContactForm() {
const analytics = useAnalytics({
apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY!
});
const handleSubmit = async (e) => {
e.preventDefault();
// Track form submission
analytics.trackEvent({
eventName: 'contact_form_submitted',
eventData: {
formType: 'contact',
source: 'homepage'
}
});
// Submit form...
};
return <form onSubmit={handleSubmit}>...</form>;
}Tracking Button Clicks
function CTAButton() {
const analytics = useAnalytics({
apiKey: process.env.NEXT_PUBLIC_LOSTKODE_API_KEY!
});
const handleClick = () => {
analytics.trackEvent({
eventName: 'cta_clicked',
eventData: {
button: 'get_started',
location: 'hero_section'
}
});
};
return <button onClick={handleClick}>Get Started</button>;
}Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
Requires support for:
fetchAPIcrypto.randomUUIDorcrypto.getRandomValuessessionStorage
Troubleshooting
No Data Showing in Dashboard
- Verify your API key is correct
- Check browser console for errors
- Ensure
respectDNTisn't blocking tracking (if you have DNT enabled in your browser) - Wait a few minutes for data to appear
TypeScript Errors
Make sure you have the required types installed:
npm install --save-dev @types/reactLicense
MIT
Support
For issues, questions, or feature requests:
- Email: [email protected]
- Documentation: https://lostkode.com/docs/analytics
- Dashboard: https://lostkode.com/dashboard
Credits
Built with ❤️ by LostKode
