npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@vexia/gtm-analytics

v1.0.0

Published

A wrapper for GTM GA4 dataLayer that works in both React and WordPress environments

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-analytics

For 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/false

TypeScript 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 implementation
  • examples/browser-example/ - Vanilla JS/WordPress implementation

Development

Build

Build all formats:

npm run build

Build ES modules only:

npm run build:esm

Build CommonJS only:

npm run build:cjs

Project 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.json

License

ISC