SDK Analytics Installer
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
What this skill does
# 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
```javascript
// 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:
```bash
cd /core/examples/nextjs
npm install @dotcms/analytics
```
### 2. Verify Installation
Check that the package was added to `package.json`:
```bash
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`
```javascript
/**
* 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`
```javascript
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):
```javascript
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`
```bash
# dotCMS Analytics Configuration
NEXT_PUBLIC_DOTCMS_SITE_AUTH=your_site_auth_key_here
NEXT_PUBLIC_DOTCMS_SERVER=https://your-dotcms-server.com
```
**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:
```bash
# 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:
```javascript
"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:
```javascript
"use client";
import { useContentAnalytics } from "@dotcms/analytics/react";
import { analyticsConfig } from "@/config/analytics.config";
function CallToActionButton() {
// โ
ALWAYS pass cRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4โv5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.