Stop Messing Up GA4 Events: A Type-Safe Analytics Library for React & Next.js
Google Analytics 4 (GA4) is powerful β but letβs be honest, the default gtag snippets get messy fast. Thatβs why I built a library @connectaryal/google-analytics β a type-safe, developer-friendly GA4 wrapper for React and Next.js.
No more guesswork, no more typos. Just clean analytics tracking. π
β¨ What You Get
β
Easy initialization with a singleton instance
β
Type-safe events (no more “pageveiw” mistakes π)
β
Ready-to-use methods for interaction, auth, and e-commerce
β
Debug mode for development
β
Works in both React & Next.js
π Step 1:Create Your Google Analytics 4 Property
Before writing any code, set up your GA4 property:
- Visit Google Analytics.
- Click Admin (bottom left) > Create Property.
- Name your property, timezone/currency, and click Next.
- Add a new Web data stream for your site.
- Copy your Measurement ID (looks like
G-XXXXXXXXXX
).
π¦ Step 2: Install the npm Package
Skip the manual gtag script and use a robust, type-safe library:
npm install @connectaryal/google-analytics
# or
yarn add @connectaryal/google-analytics
# or
pnpm add @connectaryal/google-analytics
See the package on npm: @connectaryal/google-analytics
βοΈ Step 3: Initialize Analytics
The library uses a context provider for global React integration. Wrap your app at the highest level:
import { GAProvider } from "@connectaryal/google-analytics";
function App() {
return (
<GAProvider config={{ measurementId: "G-XXXXXXXXXX" }}>
<YourApp />
</GAProvider>
);
}
Pro Tip: For Next.js, wrap your custom App
or RootLayout
component.
π Step 4: Track Events: Page Interaction, Engagement, E-commerce
π Track a Page View
import {
EventCategory,
trackPage,
} from '@connectaryal/google-analytics';
const { trackPage } = useGoogleAnalytics();
trackPage(); // auto detects
π― Custom Engagement & Conversion
import {
EventCategory,
useGoogleAnalytics,
} from '@connectaryal/google-analytics';
const { trackCustomEvent } = useGoogleAnalytics();
trackCustomEvent({
name: "video_play",
category: EventCategory.INTERACTION,
params: { video_title: "Intro Demo", video_duration: 120 },
});
π E-commerce Tracking
import { useGAEcommerce } from "@connectaryal/google-analytics";
const { trackCart, trackPurchase } = useGAEcommerce();
trackCart("add_to_cart", [
{ item_id: "SKU123", item_name: "Wireless Headphones", price: 99.99, quantity: 1 }
], 99.99);
trackPurchase("ORDER123", 199.98, [
{ item_id: "SKU123", item_name: "Wireless Headphones", price: 99.99, quantity: 2 }
]);
π Step 5. Advanced Tracking: Validated, Typed & Error-Proof
With the GATracker
class (used internally, or for advanced users):
- Every method checks for empty arrays, missing values, or invalid input.
- All events are type-checked with TypeScript.
- Debug mode logs warnings and errors clearly.
Example: Handling Validation
const tracker = new GATracker({ measurementId: "G-XXXXXXXXXX", currency: "USD", debug: true });
try {
await tracker.trackCart({
action: "add_to_cart",
items: [],
value: 99.99
});
} catch (e) {
// Will throw: "GA4: Cannot track add_to_cart with empty items"
console.error(e);
}
π οΈ Step 6: Debug Mode
Turn on debugging to see event logs:
const tracker = new GATracker({`
measurementId: "G-XXXXXXXXXX",`
debug: true,`
});
Now youβll see every event in the console π
β
Why Type Safety Matters
- No typos β “pageveiw” wonβt even compile
- Strict params β keeps you aligned with GA schema
- Reusable methods β no more raw
gtag("event", β¦)
everywhere
π Full API Reference
Hereβs everything included in the package:
Full API Reference
Method | Description |
---|---|
trackPage |
Page views |
trackCustomEvent |
Custom events |
trackItem |
Item selection/view/list |
trackCart |
Cart actions |
trackWishlist |
Wishlist actions |
trackShippingInfo |
Shipping info during checkout |
trackPaymentInfo |
Payment method selection |
trackBeginCheckout |
Begin checkout |
trackPurchase |
Purchases |
trackRefund |
Refunds |
trackPromotion |
Promotion events |
trackSearch |
Site search |
trackShare |
Content sharing |
trackVideoPlay |
Video play events |
trackFormSubmission |
Form submissions |
trackTiming |
Performance timing |
trackEngagement |
Engagement (scroll, click, etc.) |
trackLogin |
User login |
trackSignUp |
User registration |
trackException |
Exception/error events |
Why Use Type-Safe Analytics?
- No more silent failures: Type errors and validation mean you catch mistakes early.
- Enterprise-grade: Handles all GA4 e-commerce, engagement, and conversion flows.
- Debugging is simple: Errors and warnings are clear, actionable, and logged only in dev mode.
Final Thoughts
Modern analytics isnβt just about tracking everythingβitβs about tracking the right things, with clean, validated code you can trust. By starting with a GA4 property and using a type-safe, React-optimized library, your data is actionable and your integration is future-proof.
Ready to track smarter?