@thg-altitude/analytics
v0.1.8
Published
Analytics package for Astro, Next.js, and React Native
Downloads
2,975
Maintainers
Keywords
Readme
A cross-platform analytics package for Astro, Next.js, and React Native applications.
Features
- 🔄 Cross-Platform: Works with Astro, Next.js, and React Native
- 🔍 Type-Safe: Built with TypeScript for robust type checking
- ✅ Schema Validation: Uses Zod for runtime schema validation
- 🌐 Client & Server: Supports both client-side and server-side tracking
- 📊 Google Analytics Events: Pre-defined schemas for common GA4 events
Installation
# Install the package
npm install @thg-altitude/analytics
# or
yarn add @thg-altitude/analytics
# or
pnpm add @thg-altitude/analyticsUsage
Next.js
// _app.tsx or layout.tsx
import { ThgAnalyticsScript } from '@thg-altitude/analytics/next';
// For App Router (in layout.tsx)
export default function RootLayout({ children }) {
return (
<html>
<head>
<ThgAnalyticsScript />
</head>
<body>{children}</body>
</html>
);
}
// For Pages Router (in _app.tsx)
function MyApp({ Component, pageProps }) {
return (
<>
<ThgAnalyticsScript />
<Component {...pageProps} />
</>
);
}
// Using the SDK on the client side
import { createThgAnalytics } from '@thg-altitude/analytics/next';
// In a component or page
useEffect(() => {
createThgAnalytics({
debug: true,
server: {
// Optional server-side endpoint
endpoint: 'https://analytics-api.example.com/collect'
}
});
// Track page view
window.thgAnalytics.instance.userDetails({
visitorLoginState: getCustomerName() ? 'LOGGED_IN' : 'LOGGED_OUT',
visitorId: getCustomerId() || 'unknown',
visitorEmailAddress: getCustomerEmail() || 'unknown'
});
}, []);Astro
// astro.config.mjs
import { defineConfig } from 'astro/config';
import thgAnalytics from '@thg-altitude/analytics/astro';
export default defineConfig({
integrations: [
thgAnalytics({
debug: true
})
]
});<!-- In an Astro component such as the Layout or ClientInit file -->
<script>
import {
createClientAnalytics,
processStoredEvents
} from '@thg-altitude/analytics/astro';
// Initialize analytics SDK on the window object
createClientAnalytics();
window.thgAnalytics.instance.userDetails({
visitorLoginState: getCustomerName() ? 'LOGGED_IN' : 'LOGGED_OUT',
visitorId: getCustomerId() || 'unknown',
visitorEmailAddress: getCustomerEmail() || 'unknown'
});
// Proccess stored events that were sent before the SDK was initialized
processStoredEvents();
</script>Race Conditions
On Astro pages SDK functions aren't initialized on the window.thgAnalytics.instance before the page tries to invoke them. To handle this race condition, add events events to window.thgAltitude.eventStore. These stored events are then processed when the SDK is fully initialized using processStoredEvents().
window?.thgAnalytics?.instance?.viewItem({
currency: window.sessionSettings.currency,
value: price * quantity,
items: [
{
item_id,
item_name,
item_brand,
price,
quantity,
item_category,
discount
}
]
}) ||
window.thgAnalytics.eventStore.push({
name: 'viewItem',
event: {
currency: window.sessionSettings.currency,
value: price * quantity,
items: [
{
item_id,
item_name,
item_brand,
price,
quantity,
item_category,
discount
}
]
}
});Those events stored in the event store will then be handled by the processStoredEvents function called in the Layout/ClientInit file ensuring no events are lost during page load, even if they're triggered before the SDK is fully initialized.
React Native
// App.tsx
import { createThgAnalytics } from '@thg-altitude/analytics/react-native';
// Initialize analytics
const analytics = createThgAnalytics({
debug: true,
server: {
endpoint: 'https://analytics-api.example.com/collect'
}
});
// Track events
analytics.userDetails({
visitorLoginState: getCustomerName() ? 'LOGGED_IN' : 'LOGGED_OUT',
visitorId: getCustomerId() || 'unknown',
visitorEmailAddress: getCustomerEmail() || 'unknown'
});Available Events
THG Analytics provides typed methods for common Google Analytics 4 events, the schemas for events can be found here.
E-commerce Events
viewItem: Track product viewsviewItemList: Track product list viewsselectItem: Track item selection from a listaddToCart: Track add to cart eventsremoveFromCart: Track remove from cart eventsbeginCheckout: Track checkout initiationaddToWishlist: Track wishlist additionswishlistRemoved: Track wishlist removalsapplyCouponSuccess: Track successful coupon applicationsapplyCouponFail: Track failed coupon applicationsselectFreeGift: Track free gift selectionremoveFreeGift: Track free gift removalsviewFreeGift: Track free gift viewsviewPromotion: Track promotion viewsselectPromotion: Track promotion clicksfilterAdded: Track filter applicationsreadMoreClick: Track read more interactionsuserDetails: Track user state changeslogout: Track user logoutssignUp: Track user registrationspageNotFound: Track 404 errorssearch: Track search eventsreviewCreated: Track product review creationsreviewViewed: Track product review viewsreviewVoted: Track votes on product reviewsreviewReported: Track reports on product reviews
Schema Validation
THG Analytics uses Zod for schema validation, providing helpful warnings when event data doesn't match the expected schema:
// This will work and send the event
analytics.userDetails({
visitorLoginState: getCustomerName() ? 'LOGGED_IN' : 'LOGGED_OUT',
visitorId: getCustomerId() || 'unknown',
visitorEmailAddress: getCustomerEmail() || 'unknown'
});
// This will log a warning and not send the event
analytics.userDetails({
visitorLoginState: getCustomerName() ? 'LOGGED_IN' : 'LOGGED_OUT',
visitorId: getCustomerId() || 'unknown',
// visitorEmailAddress missing - will not send event
});License
MIT
