Gatsby plugin that provides comprehensive Google Global Site Tag (gtag.js) integration for tracking across multiple Google services
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Global gtag function for firing custom events and conversions with Google tracking services.
The plugin makes the global gtag function available for custom event tracking across all configured Google services.
/**
* Global gtag function for custom event tracking and configuration
* Available on window object after plugin initialization
* @param command - The gtag command ("event", "config", "js")
* @param eventNameOrTrackingIdOrDate - Event name, tracking ID, or Date object depending on command
* @param parameters - Optional event parameters and configuration
*/
declare function gtag(
command: "event" | "config" | "js",
eventNameOrTrackingIdOrDate: string | Date,
parameters?: EventParameters | GtagConfig
): void;
interface EventParameters {
/** Category for grouping events (e.g., "engagement", "conversion") */
event_category?: string;
/** Human-readable label for the event */
event_label?: string;
/** Specific tracking ID to send event to (targets specific service) */
send_to?: string;
/** Transport method for event delivery ("beacon" for reliability) */
transport_type?: string;
/** Callback function executed after event is sent */
event_callback?: () => void;
/** Custom dimensions and metrics */
custom_parameter_1?: string;
custom_parameter_2?: number;
/** Any additional gtag event parameters */
[key: string]: any;
}Usage Examples:
// Guard against SSR - gtag only available in browser
if (typeof window !== "undefined" && window.gtag) {
// Track button click
window.gtag("event", "click", {
event_category: "engagement",
event_label: "header_cta_button",
});
}// Track purchase conversion
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", "purchase", {
event_category: "ecommerce",
event_label: "checkout_complete",
value: 99.99,
currency: "USD",
transaction_id: "T12345",
});
}// Send event to specific Google Ads account
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", "conversion", {
send_to: "AW-CONVERSION_ID/CONVERSION_LABEL",
value: 50.0,
currency: "USD",
});
}// Track download with callback
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", "download", {
event_category: "file",
event_label: "user_manual.pdf",
transport_type: "beacon",
event_callback: function () {
console.log("Download event tracked successfully");
// Additional logic after tracking
},
});
}import React from "react";
export default function TrackedButton() {
const handleClick = () => {
// Custom event tracking
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", "click", {
event_category: "ui_interaction",
event_label: "newsletter_signup",
transport_type: "beacon",
});
}
// Your application logic
console.log("Button clicked");
};
return (
<button onClick={handleClick}>
Subscribe to Newsletter
</button>
);
}import { useCallback } from "react";
export function useGtagEvent() {
const trackEvent = useCallback((eventName, parameters = {}) => {
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", eventName, parameters);
}
}, []);
return trackEvent;
}
// Usage in component
export default function MyComponent() {
const trackEvent = useGtagEvent();
const handleFormSubmit = () => {
trackEvent("form_submit", {
event_category: "engagement",
event_label: "contact_form",
});
};
return <form onSubmit={handleFormSubmit}>...</form>;
}The plugin automatically tracks pageview events on route changes using Gatsby's onRouteUpdate browser API. This tracking only works in production mode.
// Automatic pageview tracking (handled internally by plugin)
// Fires on every Gatsby route change via onRouteUpdate
window.gtag("event", "page_view", {
page_path: location.pathname + location.search + location.hash
});requestAnimationFrame (or 32ms setTimeout fallback) to ensure React helmet updates completeRoute tracking behavior can be configured via plugin options:
pluginConfig.exclude to skip tracking on specific paths (supports glob patterns)pluginConfig.delayOnRouteUpdate to add additional delay after React lifecyclepluginConfig.respectDNT to respect browser DNT settings during SSR injection// Engagement events
gtag("event", "click", { event_category: "engagement" });
gtag("event", "scroll", { event_category: "engagement" });
gtag("event", "search", { event_category: "engagement", search_term: "query" });
// Conversion events
gtag("event", "sign_up", { event_category: "conversion" });
gtag("event", "purchase", { event_category: "ecommerce", value: 99.99 });
gtag("event", "generate_lead", { event_category: "conversion" });// Specific conversion tracking for Google Ads
gtag("event", "conversion", {
send_to: "AW-CONVERSION_ID/CONVERSION_LABEL",
value: 1.0,
currency: "USD",
});The plugin uses the config command internally to initialize tracking IDs:
// Plugin automatically executes config commands for each trackingId
gtag("config", "GA-TRACKING_ID", {
optimize_id: "OPT_CONTAINER_ID",
anonymize_ip: true,
send_page_view: false // Plugin disables automatic pageviews
});The js command initializes the gtag library (handled automatically by plugin):
// Plugin automatically executes during SSR
gtag("js", new Date());Always guard gtag calls against server-side rendering:
// ✅ Correct - guards against SSR
if (typeof window !== "undefined" && window.gtag) {
window.gtag("event", "click", { event_category: "engagement" });
}
// ❌ Incorrect - will cause SSR errors
window.gtag("event", "click", { event_category: "engagement" });