sdk-analytics-installer

0
0
Source

Use this skill when the user asks to install, configure, or set up @dotcms/analytics, sdk-analytics, analytics SDK, add analytics tracking, or mentions installing analytics in Next.js or React projects

Install

mkdir -p .claude/skills/sdk-analytics-installer && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6036" && unzip -o skill.zip -d .claude/skills/sdk-analytics-installer && rm skill.zip

Installs to .claude/skills/sdk-analytics-installer

About this skill

DotCMS SDK Analytics Installation Guide

This skill provides step-by-step instructions for installing and configuring the @dotcms/analytics SDK in the Next.js example project at /core/examples/nextjs.

Overview

The @dotcms/analytics SDK is dotCMS's official JavaScript library for tracking content-aware events and analytics. It provides:

  • Automatic page view tracking
  • Conversion tracking (purchases, downloads, sign-ups, etc.)
  • Custom event tracking
  • Session management (30-minute timeout)
  • Anonymous user identity tracking
  • UTM campaign parameter tracking
  • Event batching/queuing for performance

🚨 Important: Understanding the Analytics Components

CRITICAL: useContentAnalytics() ALWAYS requires config as a parameter. The hook does NOT use React Context.

Component Roles

  1. <DotContentAnalytics /> - Auto Page View Tracker

    • Only purpose: Automatically track pageviews on route changes
    • NOT a React Context Provider
    • Does NOT provide config to child components
    • Place in root layout for automatic pageview tracking
  2. useContentAnalytics(config) - Manual Tracking Hook

    • Used for custom event tracking
    • ALWAYS requires config parameter
    • Import centralized config in each component that uses it

Correct Usage Pattern

// 1. Create centralized config file (once)
// /src/config/analytics.config.js
export const analyticsConfig = {
  siteAuth: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_SITE_KEY,
  server: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_HOST,
  autoPageView: true,
  debug: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_DEBUG === "true",
};

// 2. Add DotContentAnalytics to layout for auto pageview tracking (optional)
// /src/app/layout.js
import { DotContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

<DotContentAnalytics config={analyticsConfig} />;

// 3. Import config in every component that uses the hook
// /src/components/MyComponent.js
import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

const { track } = useContentAnalytics(analyticsConfig); // ✅ Config required!

Why centralize config? While you must import it in each component, centralizing prevents duplication and makes updates easier.

Quick Setup Summary

Here's the complete setup flow:

1. Install package
   └─> npm install @dotcms/analytics

2. Create centralized config file
   └─> /src/config/analytics.config.js
       └─> export const analyticsConfig = { siteAuth, server, debug, ... }

3. (Optional) Add DotContentAnalytics for auto pageview tracking
   └─> /src/app/layout.js
       └─> import { analyticsConfig } from "@/config/analytics.config"
       └─> <DotContentAnalytics config={analyticsConfig} />

4. Import config in EVERY component that uses the hook
   └─> /src/components/MyComponent.js
       └─> import { analyticsConfig } from "@/config/analytics.config"
       └─> const { track } = useContentAnalytics(analyticsConfig) // ✅ Config required!

Key Benefits of Centralized Config:

  • ✅ Single source of truth for configuration values
  • ✅ Easy to update environment variables in one place
  • ✅ Consistent config across all components
  • ✅ Better than duplicating config in every file

Installation Steps

1. Install the Package

Navigate to the Next.js example directory and install the package:

cd /core/examples/nextjs
npm install @dotcms/analytics

2. Verify Installation

Check that the package was added to package.json:

grep "@dotcms/analytics" package.json

Expected output: "@dotcms/analytics": "latest" or similar version.

3. Create Centralized Analytics Configuration

Create a dedicated configuration file to centralize your analytics settings. This makes it easier to maintain and reuse across your application.

File: /core/examples/nextjs/src/config/analytics.config.js

/**
 * Centralized analytics configuration for dotCMS Content Analytics
 *
 * This configuration is used by:
 * - DotContentAnalytics provider in layout.js
 * - useContentAnalytics() hook when used standalone (optional)
 *
 * Environment variables required:
 * - NEXT_PUBLIC_DOTCMS_ANALYTICS_SITE_KEY
 * - NEXT_PUBLIC_DOTCMS_ANALYTICS_HOST
 * - NEXT_PUBLIC_DOTCMS_ANALYTICS_DEBUG (optional)
 */
export const analyticsConfig = {
  siteAuth: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_SITE_KEY,
  server: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_HOST,
  autoPageView: true, // Automatically track page views on route changes
  debug: process.env.NEXT_PUBLIC_DOTCMS_ANALYTICS_DEBUG === "true",
  queue: {
    eventBatchSize: 15, // Send when 15 events are queued
    flushInterval: 5000, // Or send every 5 seconds (ms)
  },
};

Benefits of this approach:

  • ✅ Single source of truth for analytics configuration
  • ✅ Easy to import and reuse across components
  • ✅ Centralized environment variable management
  • ✅ Type-safe and IDE autocomplete friendly
  • ✅ Easy to test and mock in unit tests

4. Configure Analytics in Next.js Layout

Update the root layout file to include the analytics provider using the centralized config.

File: /core/examples/nextjs/src/app/layout.js

import { Inter } from "next/font/google";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  );
}

Updated with Analytics (using centralized config):

import { Inter } from "next/font/google";
import { DotContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body className={inter.className}>
        <DotContentAnalytics config={analyticsConfig} />
        {children}
      </body>
    </html>
  );
}

4. Add Environment Variables

Create or update .env.local file in the Next.js project root:

File: /core/examples/nextjs/.env.local

# dotCMS Analytics Configuration
NEXT_PUBLIC_DOTCMS_AUTH_TOKEN={GENERATE TOKEN FROM USER PORTLET API ACCESS TOKEN}
NEXT_PUBLIC_DOTCMS_HOST={URL WHERE DOTCMS IS RUNNING}
NEXT_PUBLIC_DOTCMS_SITE_ID={SITE IDENTIFIER}
NEXT_PUBLIC_DOTCMS_ANALYTICS_SITE_KEY={GENERATE KEY FROM CONTENT ANALYTICS APP}
NEXT_PUBLIC_DOTCMS_ANALYTICS_HOST={SITE IDENTIFIER}
NEXT_PUBLIC_EXPERIMENTS_API_KEY={GENERATED KEY FROM THE EXPERIMENTS APP}
NEXT_PUBLIC_DOTCMS_MODE='production'
NODE_TLS_REJECT_UNAUTHORIZED=0

Important: Replace your_site_auth_key_here with your actual dotCMS Analytics site auth key. This can be obtained from the Analytics app in your dotCMS instance.

5. Add .env.local to .gitignore

Ensure the environment file is not committed to version control:

# Check if already ignored
grep ".env.local" /core/examples/nextjs/.gitignore

# If not present, add it
echo ".env.local" >> /core/examples/nextjs/.gitignore

Usage Examples

Basic Setup (Automatic Page Views)

With the configuration above, page views are automatically tracked on every route change. No additional code needed!

Manual Page View with Custom Data

Track page views with additional context:

"use client";

import { useEffect } from "react";
import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

function MyComponent() {
  // ✅ ALWAYS pass config - import from centralized config file
  const { pageView } = useContentAnalytics(analyticsConfig);

  useEffect(() => {
    // Track page view with custom data
    pageView({
      contentType: "blog",
      category: "technology",
      author: "john-doe",
      wordCount: 1500,
    });
  }, []);

  return <div>Content here</div>;
}

Track Custom Events

Track specific user interactions:

"use client";

import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

function CallToActionButton() {
  // ✅ ALWAYS pass config - import from centralized config file
  const { track } = useContentAnalytics(analyticsConfig);

  const handleClick = () => {
    // Track custom event
    track("cta-click", {
      button: "Buy Now",
      location: "hero-section",
      price: 299.99,
    });
  };

  return <button onClick={handleClick}>Buy Now</button>;
}

Form Submission Tracking

"use client";

import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

function ContactForm() {
  const { track } = useContentAnalytics(analyticsConfig);

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Track form submission
    track("form-submit", {
      formName: "contact-form",
      formType: "lead-gen",
      source: "homepage",
    });

    // Submit form...
  };

  return <form onSubmit={handleSubmit}>{/* Form fields */}</form>;
}

Video/Media Interaction Tracking

"use client";

import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";

function VideoPlayer({ videoId }) {
  const { track } = useContentAnalytics(analyticsConfig);

  const handlePlay = () => {
    track("video-play", {
      videoId,
      duration: 120,
      autoplay: false,
    });
  };

  const handleComplete = () => {
    track("video-complete", {
      videoId,
      watchPercentage: 100,
    });
  };

  return (
    <video onPlay={handlePlay} onEnded={handleComplete}>
      {/* Video sources */}
    </video>
  );
}

E-commerce Product View Tracking

"use client";

import { u

---

*Content truncated.*

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.