@vexia/gtm-analytics
v1.0.0
Published
A wrapper for GTM GA4 dataLayer that works in both React and WordPress environments
Maintainers
Readme
Vexia GTM Analytics
A lightweight TypeScript wrapper for GTM GA4 dataLayer that works seamlessly in both React and WordPress environments.
Features
- 🚀 Simple, clean API for GTM dataLayer
- 📘 Full TypeScript support with exported types
- 🎯 Generic dataLayer wrapper - not opinionated about events
- 🔄 Works in both ESM and browser (IIFE) environments
- 🌐 Auto-initializes for WordPress/script tag usage
- ⚡ Zero-config usage - works without calling
init() - �️ Safe for multiple initialization calls (idempotent)
- �🐛 Built-in debug mode
- 📦 Tiny bundle size (~1.5kb minified)
Installation
For React/NPM Projects
npm install @vexia/gtm-analyticsFor WordPress Projects
Option 1: Via CDN (Recommended)
Include the script from a CDN (automatically available after npm publish):
<!-- From jsDelivr CDN (recommended) -->
<script src="https://cdn.jsdelivr.net/npm/@vexia/gtm-analytics@1/dist/browser.js"></script>
<!-- Or from unpkg CDN -->
<script src="https://unpkg.com/@vexia/gtm-analytics@1/dist/browser.js"></script>Option 2: Self-hosted
Download browser.js from the releases page or from npm, then include it:
<script src="/path/to/browser.js"></script>The bundled browser.js file contains all the code in a single file, ready to use in any browser environment.
Usage
React/NPM Usage
Option 1: Initialize with config first (recommended)
import VexiaAnalytics from '@vexia/gtm-analytics';
// Initialize with options and global metadata
VexiaAnalytics.init({
debug: true,
dataLayerName: 'dataLayer',
metadata: {
// These properties will be automatically added to ALL events
environment: 'production',
app_version: '1.2.3',
user_type: 'premium'
}
});
// Push any data to dataLayer
// Metadata is automatically included!
VexiaAnalytics.push({
event: 'page_view',
page_title: 'Home',
page_path: '/'
});
// Actual dataLayer push: { environment: 'production', app_version: '1.2.3', user_type: 'premium', event: 'page_view', page_title: 'Home', page_path: '/' }
// Or use the event helper - metadata is also included
VexiaAnalytics.event('button_click', {
button_name: 'cta_signup',
button_location: 'header'
});
// Actual dataLayer push: { environment: 'production', app_version: '1.2.3', user_type: 'premium', event: 'button_click', button_name: 'cta_signup', button_location: 'header' }Option 2: Zero-config usage (also works!)
import VexiaAnalytics from '@vexia/gtm-analytics';
// Just use it - auto-initializes with defaults if not initialized
VexiaAnalytics.event('button_click', {
button_name: 'cta_signup'
});
VexiaAnalytics.push({
event: 'page_view',
page_title: 'Home'
});
// No init() needed! Works out of the box.More examples:
import VexiaAnalytics from '@vexia/gtm-analytics';
// Push custom data structures
VexiaAnalytics.push({
user_id: '12345',
user_type: 'premium'
});
// You can push anything your GTM setup expects
VexiaAnalytics.push({
event: 'purchase',
ecommerce: {
transaction_id: 'T12345',
value: 99.99,
currency: 'USD',
items: [
{
item_id: 'SKU123',
item_name: 'Product Name',
price: 99.99,
quantity: 1
}
]
}
});WordPress/Script Tag Usage
When included via script tag, the library automatically initializes and exposes itself on the window object:
<!-- Include from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@vexia/gtm-analytics@1/dist/browser.js"></script>
<script>
// The library is automatically available as window.VexiaAnalytics
// Enable debug mode
VexiaAnalytics.init({ debug: true });
// Push events
VexiaAnalytics.event('button_click', {
button_name: 'download_pdf'
});
// Push any data
VexiaAnalytics.push({
event: 'page_view',
page_title: document.title
});
</script>API Reference
init(options?: AnalyticsConfig)
Initialize the library with optional configuration.
The library is idempotent - calling init() multiple times is safe:
- First call: Full initialization
- Subsequent calls without options: Skipped with log message
- Subsequent calls with options: Updates configuration
interface AnalyticsConfig {
debug?: boolean; // Enable debug logging (default: false)
dataLayerName?: string; // Custom dataLayer name (default: 'dataLayer')
metadata?: Record<string, any>; // Global properties added to ALL events (default: {})
}Example:
import VexiaAnalytics from '@vexia/gtm-analytics';
VexiaAnalytics.init({
debug: true,
dataLayerName: 'dataLayer',
metadata: {
environment: 'production',
app_version: '1.2.3',
user_id: '12345'
}
});
// Safe to call again - won't re-initialize
VexiaAnalytics.init(); // Logs: "Analytics already initialized, skipping..."
// Update metadata after initialization
VexiaAnalytics.setConfig({
metadata: {
...VexiaAnalytics.getConfig().metadata,
user_type: 'premium'
}
});isInit(): boolean
Check if the library has been initialized.
import VexiaAnalytics from '@vexia/gtm-analytics';
if (!VexiaAnalytics.isInit()) {
VexiaAnalytics.init({ debug: true });
}push(data: DataLayerEvent | any)
Push any data to the dataLayer. This is the core function that gives you full flexibility.
Global metadata is automatically included in all pushes!
import VexiaAnalytics from '@vexia/gtm-analytics';
// If you initialized with metadata
VexiaAnalytics.init({
metadata: {
environment: 'prod',
app_version: '1.0.0'
}
});
// This push...
VexiaAnalytics.push({
event: 'custom_event',
category: 'engagement',
action: 'click'
});
// Actually pushes this to dataLayer:
// {
// environment: 'prod',
// app_version: '1.0.0',
// event: 'custom_event',
// category: 'engagement',
// action: 'click'
// }Note: Event-specific data takes precedence over metadata if there are duplicate keys.
event(eventName: string, params?: GA4EventParams)
Convenience function to push events with parameters.
import VexiaAnalytics from '@vexia/gtm-analytics';
VexiaAnalytics.event('sign_up', {
method: 'email',
success: true
});
// Equivalent to:
VexiaAnalytics.push({
event: 'sign_up',
method: 'email',
success: true
});setConfig(options: Partial<AnalyticsConfig>)
Update configuration after initialization.
import VexiaAnalytics from '@vexia/gtm-analytics';
VexiaAnalytics.setConfig({ debug: true });getConfig(): AnalyticsConfig
Get the current configuration.
import VexiaAnalytics from '@vexia/gtm-analytics';
const config = VexiaAnalytics.getConfig();
console.log(config.debug); // true/falseTypeScript Types
The library exports TypeScript types for better development experience:
import type {
AnalyticsConfig,
DataLayerEvent,
GA4EventParams
} from '@vexia/gtm-analytics';Examples
Check out the examples/ directory for complete working examples:
examples/nextjs-example/- Next.js/React implementationexamples/browser-example/- Vanilla JS/WordPress implementation
Development
Build
Build all formats:
npm run buildBuild ES modules only:
npm run build:esmBuild CommonJS only:
npm run build:cjsProject Structure
├── src/
│ ├── main.ts # Core library logic
│ └── index.ts # Main entry point
├── dist/ # Built files (generated)
│ ├── index.js # ES module
│ ├── index.cjs # CommonJS module
│ ├── browser.js # Bundled browser version (IIFE)
│ └── *.d.ts # TypeScript definitions
├── examples/ # Usage examples
│ ├── nextjs-example/ # Next.js/React example
│ └── browser-example/ # Vanilla JS/WordPress example
├── package.json
└── tsconfig.jsonLicense
ISC
