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:

  1. Visit Google Analytics.
  2. Click Admin (bottom left) > Create Property.
  3. Name your property, timezone/currency, and click Next.
  4. Add a new Web data stream for your site.
  5. 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?

πŸ‘‰ Found issue or want to contribute.

Similar Posts