### Install vanilla-cookieconsent
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Install the vanilla-cookieconsent library using npm.
```bash
npm install vanilla-cookieconsent
```
--------------------------------
### Install analytics-script
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Install the library using npm or pnpm.
```bash
npm install analytics-script
# or
pnpm add analytics-script
```
--------------------------------
### Install react-cookie-consent
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Install the react-cookie-consent library using npm.
```bash
npm install react-cookie-consent
```
--------------------------------
### Install analytics-script Package
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Use npm or pnpm to install the analytics-script package. This is the first step before integrating any analytics service.
```bash
npm i analytics-script
```
```bash
pnpm add analytics-script
```
--------------------------------
### Setup Mixpanel Analytics
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Inlines the Mixpanel browser snippet and initializes Mixpanel with the provided token. Supports `autocapture` for automatic interaction tracking and `record_sessions_percent` for session recording configuration. Place this in your app's layout head.
```tsx
import { Mixpanel } from 'analytics-script';
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Setup Crisp Chat Widget
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Inlines the Crisp Chat loader script using the provided `websiteId`. The widget loads asynchronously and attaches a live chat bubble to the page. Ensure this is placed in your app's layout head.
```tsx
import { Crisp } from 'analytics-script';
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
--------------------------------
### Next.js API Route for Server-Side Tracking
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Example of integrating `trackDataFastGoalServer` into a Next.js API route for handling tracking requests from the client.
```tsx
// app/api/track/route.ts
import { trackDataFastGoalServer } from 'analytics-script';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const { visitorId, goalName, metadata } = await request.json();
const result = await trackDataFastGoalServer({
apiKey: process.env.DATAFAST_API_KEY!,
visitorId,
goalName,
metadata,
});
if (result.success) {
return NextResponse.json({ success: true });
} else {
return NextResponse.json(
{ success: false, error: result.error },
{ status: 500 }
);
}
}
```
--------------------------------
### Google Analytics with vanilla-cookieconsent
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Example of integrating Google Analytics with vanilla-cookieconsent for managing user consent.
```APIDOC
## Google Analytics with vanilla-cookieconsent
### Description
This example shows how to integrate Google Analytics with `vanilla-cookieconsent` to manage user consent for analytics storage.
### Setup
1. Install `vanilla-cookieconsent`:
```bash
npm install vanilla-cookieconsent
```
### Usage
```tsx
'use client';
import { GoogleAnalytics } from 'analytics-script';
import { useEffect } from 'react';
import 'vanilla-cookieconsent/dist/cookieconsent.css';
import * as CookieConsent from 'vanilla-cookieconsent';
export default function App() {
useEffect(() => {
CookieConsent.run({
categories: {
necessary: {
enabled: true,
readOnly: true
},
analytics: {
enabled: false
}
},
language: {
default: 'en',
translations: {
en: {
consentModal: {
title: 'We use cookies',
description: 'Cookie modal description',
acceptAllBtn: 'Accept all',
acceptNecessaryBtn: 'Reject all',
showPreferencesBtn: 'Manage preferences'
},
preferencesModal: {
title: 'Cookie preferences',
acceptAllBtn: 'Accept all',
acceptNecessaryBtn: 'Reject all',
savePreferencesBtn: 'Save preferences',
sections: [
{
title: 'Analytics cookies',
description: 'These cookies help us improve our website.',
linkedCategory: 'analytics'
}
]
}
}
}
},
onConsent: () => {
if (CookieConsent.acceptedCategory('analytics')) {
window.gtag?.('consent', 'update', {
analytics_storage: 'granted'
});
}
},
onChange: () => {
if (CookieConsent.acceptedCategory('analytics')) {
window.gtag?.('consent', 'update', {
analytics_storage: 'granted'
});
} else {
window.gtag?.('consent', 'update', {
analytics_storage: 'denied'
});
}
}
});
}, []);
return (
<>
>
);
}
```
```
--------------------------------
### Google Analytics with react-cookie-consent
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Example of integrating Google Analytics with react-cookie-consent for managing user consent.
```APIDOC
## Google Analytics with react-cookie-consent
### Description
This example demonstrates how to integrate Google Analytics with the `react-cookie-consent` library to manage user consent for analytics storage.
### Setup
1. Install `react-cookie-consent`:
```bash
npm install react-cookie-consent
```
### Usage
```tsx
import { GoogleAnalytics, updateGoogleConsent } from 'analytics-script';
import CookieConsent from 'react-cookie-consent';
export default function App() {
return (
<>
{
updateGoogleConsent({
analytics_storage: 'granted'
});
}}
style={{ background: '#2B373B' }}
buttonStyle={{ background: '#4CAF50', color: '#fff', fontSize: '14px' }}
declineButtonStyle={{ background: '#f44336', color: '#fff', fontSize: '14px' }}
>
This website uses cookies to enhance the user experience.
>
);
}
```
```
--------------------------------
### MoneyFast Attribution Helpers
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Provides functions to access and manage MoneyFast attribution data, including getting raw data, formatted metadata for Stripe, and clearing the attribution cookie.
```tsx
import { getMoneyFastAttribution, getMoneyFastMeta, clearMoneyFastAttribution } from 'analytics-script';
// Get raw attribution data
const data = getMoneyFastAttribution();
// { moneyfast_ref: 'google', moneyfast_campaign: 'summer', moneyfast_device: 'desktop', ... }
// Get data formatted for Stripe Checkout metadata (adds exit_page, removes timestamp)
const meta = getMoneyFastMeta();
// Clear attribution cookie
clearMoneyFastAttribution();
```
--------------------------------
### Get Stripe-Ready MoneyFast Attribution Metadata
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Formats attribution data for Stripe Checkout metadata, adding `exit_page` and removing the timestamp. This metadata should be passed to both `metadata` and `subscription_data.metadata` when creating a Stripe Checkout Session.
```tsx
// app/api/checkout/route.ts
import { getMoneyFastMeta } from 'analytics-script'; // client-side helper
// NOTE: call getMoneyFastMeta() in the browser, then send meta to this API route
// --- Client component ---
'use client';
import { getMoneyFastMeta } from 'analytics-script';
async function startCheckout(priceId: string) {
const meta = getMoneyFastMeta();
// { moneyfast_ref: 'google', moneyfast_campaign: 'summer', exit_page: '/pricing' }
const res = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ priceId, metadata: meta }),
});
const { url } = await res.json();
window.location.href = url;
}
// --- API Route (server) ---
// import Stripe from 'stripe';
// const session = await stripe.checkout.sessions.create({
// line_items: [{ price: priceId, quantity: 1 }],
// metadata: meta, // for one-time payments
// subscription_data: { metadata: meta }, // for subscriptions — required separately!
// mode: 'subscription',
// success_url: `${process.env.NEXT_PUBLIC_URL}/success`,
// cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,
// });
```
--------------------------------
### Setup Google Analytics 4 with GDPR Consent
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Injects the Google Tag Manager loader script and initializes gtag with optional GDPR Consent Mode v2. Sets default consent states before the config call to ensure no data is sent until consent is granted. Ensure this is placed in your app's layout head.
```tsx
import { GoogleAnalytics } from 'analytics-script';
// app/layout.tsx — basic setup
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{/* GDPR-compliant: deny all by default, update after user accepts */}
{children}
);
}
```
--------------------------------
### - Plausible Analytics (with initialization)
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Renders the Plausible script asynchronously along with an inline initialization block for setting up a command queue.
```APIDOC
## - Plausible Analytics (with initialization)
### Description
Renders two `
//
```
--------------------------------
### Clear MoneyFast Attribution Cookie
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Clears the MoneyFast attribution cookie. Call this after a successful purchase to ensure the next session starts fresh.
```tsx
'use client';
import { clearMoneyFastAttribution } from 'analytics-script';
import { useEffect } from 'react';
// pages/success.tsx — called on the post-checkout success page
export default function SuccessPage() {
useEffect(() => {
// Clear attribution after conversion is recorded
clearMoneyFastAttribution();
}, []);
return
Thank you for your purchase!
;
}
```
--------------------------------
### clearMoneyFastAttribution()
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Clears the MoneyFast attribution cookie. This function should be called after a successful purchase to ensure the next user session starts with fresh attribution data.
```APIDOC
## `clearMoneyFastAttribution()`
### Description
Clears the MoneyFast attribution cookie. Call this after a successful purchase so the next session starts fresh.
### Usage
```tsx
'use client';
import { clearMoneyFastAttribution } from 'analytics-script';
import { useEffect } from 'react';
export default function SuccessPage() {
useEffect(() => {
clearMoneyFastAttribution();
}, []);
return
Thank you for your purchase!
;
}
```
```
--------------------------------
###
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Inlines the Mixpanel browser snippet and calls `mixpanel.init()` with the provided token. Supports `autocapture` and `record_sessions_percent`.
```APIDOC
## `` — Mixpanel Analytics
Inlines the Mixpanel browser snippet and calls `mixpanel.init()` with the provided token. Supports `autocapture` (automatic interaction tracking) and `record_sessions_percent` (`true` = 100% session recording, `false` = 0%).
### Usage
```tsx
import { Mixpanel } from 'analytics-script';
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
### Rendered
Inline `
```
```
--------------------------------
### Reliable Tracking with DataFastQueue and DataFast
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Ensure events are captured reliably, even if triggered before the main script loads, by using `DataFastQueue` before the `DataFast` component in your HTML head.
```tsx
import { DataFastQueue, DataFast } from 'analytics-script';
// In your layout or _app.tsx
```
--------------------------------
### Track Custom Goals Client-Side
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Use `trackDataFastGoal` for simple or advanced client-side goal tracking. Pass custom parameters for more detailed event information.
```tsx
import { trackDataFastGoal } from 'analytics-script';
// Simple goal tracking
// Advanced usage with custom parameters
```
--------------------------------
### Tracking Custom Goals/Events
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Client-side and server-side methods for tracking custom goals and events. Supports simple goal tracking, advanced usage with custom parameters, and server-side tracking with API keys and metadata.
```APIDOC
## Client-side Tracking
### Description
Track custom goals and events directly from your client-side application using the `trackDataFastGoal` function.
### Function Signature
`trackDataFastGoal(goalName: string, parameters?: object)`
### Parameters
- `goalName` (string) - The name of the goal or event to track.
- `parameters` (object, optional) - Custom parameters to associate with the goal.
### Example
```tsx
import { trackDataFastGoal } from 'analytics-script';
// Simple goal tracking
trackDataFastGoal('signup');
// With custom parameters
trackDataFastGoal('purchase', {
product_id: 'prod_123',
amount: 99.99
});
```
## Server-side Tracking
### Description
Track goals and events from your backend code, API routes, or server actions using `trackDataFastGoalServer`.
### Function Signature
`trackDataFastGoalServer(options: { apiKey: string, visitorId: string, goalName: string, metadata?: object, apiUrl?: string })`
### Parameters
- `apiKey` (string) - Your DataFast API key.
- `visitorId` (string) - The unique identifier for the visitor.
- `goalName` (string) - The name of the goal or event to track.
- `metadata` (object, optional) - Additional data to associate with the goal.
- `apiUrl` (string, optional) - Custom URL for the DataFast API endpoint (e.g., for self-hosted or proxy).
### Example
```tsx
import { trackDataFastGoalServer } from 'analytics-script';
const result = await trackDataFastGoalServer({
apiKey: 'your_api_key',
visitorId: 'visitor_123',
goalName: 'newsletter_signup',
metadata: { name: 'John Doe' },
apiUrl: 'https://custom.datafa.st/api/v1/goals'
});
if (result.success) {
console.log('Goal tracked successfully');
} else {
console.error('Error tracking goal:', result.error);
}
```
```
--------------------------------
### getMoneyFastMeta()
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Returns attribution data formatted for use as Stripe Checkout metadata — adds `exit_page` and removes the timestamp field. Pass to both `metadata` and `subscription_data.metadata` when creating a Checkout Session.
```APIDOC
## `getMoneyFastMeta()` — Get Stripe-Ready Attribution Metadata
Returns attribution data formatted for use as Stripe Checkout metadata — adds `exit_page` and removes the timestamp field. Pass to both `metadata` and `subscription_data.metadata` when creating a Checkout Session.
### Usage
```tsx
// app/api/checkout/route.ts
import { getMoneyFastMeta } from 'analytics-script'; // client-side helper
// NOTE: call getMoneyFastMeta() in the browser, then send meta to this API route
// --- Client component ---
'use client';
import { getMoneyFastMeta } from 'analytics-script';
async function startCheckout(priceId: string) {
const meta = getMoneyFastMeta();
// { moneyfast_ref: 'google', moneyfast_campaign: 'summer', exit_page: '/pricing' }
const res = await fetch('/api/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ priceId, metadata: meta }),
});
const { url } = await res.json();
window.location.href = url;
}
// --- API Route (server) ---
// import Stripe from 'stripe';
// const session = await stripe.checkout.sessions.create({
// line_items: [{ price: priceId, quantity: 1 }],
// metadata: meta, // for one-time payments
// subscription_data: { metadata: meta }, // for subscriptions — required separately!
// mode: 'subscription',
// success_url: `${process.env.NEXT_PUBLIC_URL}/success`,
// cancel_url: `${process.env.NEXT_PUBLIC_URL}/pricing`,
// });
```
```
--------------------------------
### trackDataFastGoal()
Source: https://context7.com/iamcorey/analytics-script/llms.txt
Fires a named goal/event through the DataFast tracker on the client-side. Accepts an optional metadata object for richer analytics. This function is safe to call during SSR as it guards against `window` being undefined.
```APIDOC
## `trackDataFastGoal()` — Client-side Event Tracking (DataFast)
Fires a named goal/event through the DataFast tracker already loaded on the page (`window.datafast`). Accepts an optional metadata object for richer analytics. Safe to call during SSR — it guards against `window` being undefined.
### Parameters
- **goalName** (string) - Required - The name of the goal or event to track.
- **metadata** (object) - Optional - An object containing additional data to send with the event.
### Example Usage
```tsx
'use client';
import { trackDataFastGoal } from 'analytics-script';
// Simple goal
function SignupButton() {
return (
);
}
// Goal with metadata
function CheckoutButton({ product }: { product: { id: string; name: string; price: number } }) {
const handleClick = () => {
trackDataFastGoal('checkout_initiated', {
product_id: product.id,
product_name: product.name,
amount: product.price,
currency: 'USD',
});
};
return ;
}
```
```
--------------------------------
### Umami Analytics
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Integrate Umami Analytics by providing your website ID and script URL.
```APIDOC
## Umami
### Description
Integrate Umami Analytics by providing your website ID and script URL.
### Component
Umami
### Props
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Props
- `websiteId` (string) - Required - Your Umami website ID (or use env: `NEXT_PUBLIC_UMAMI_WEBSITE_ID`)
- `scriptUrl` (string) - Required - Umami script URL (or use env: `NEXT_PUBLIC_UMAMI_SCRIPT_URL`)
- `defer` (boolean) - Optional - Defer script loading (default: `true`)
- `allowLocalhost` (boolean) - Optional - Enable in development (default: `false`)
```
--------------------------------
### Crisp Chat Integration
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Integrate Crisp Chat into your application using the `Crisp` component, requiring your Crisp website ID.
```APIDOC
## Crisp Chat Integration
### Description
Embed Crisp Chat functionality into your application using the `Crisp` component. You need your Crisp website ID to initialize it.
### Component Usage
```tsx
import { Crisp } from 'analytics-script';
```
### Props
- `websiteId` (string) - Your Crisp website ID. Can also be set via the environment variable `NEXT_PUBLIC_CRISP_WEBSITE_ID`.
- `allowLocalhost` (boolean, optional) - Enable tracking on localhost. Defaults to `false`.
```
--------------------------------
### Microsoft Clarity Integration
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Integrate Microsoft Clarity for user behavior analytics using the `Clarity` component, requiring your Clarity project ID.
```APIDOC
## Microsoft Clarity Integration
### Description
Integrate Microsoft Clarity to analyze user behavior with the `Clarity` component. Provide your Clarity project ID for initialization.
### Component Usage
```tsx
import { Clarity } from 'analytics-script';
```
### Props
- `projectId` (string) - Your Microsoft Clarity project ID. Can also be set via the environment variable `NEXT_PUBLIC_CLARITY_PROJECT_ID`.
- `allowLocalhost` (boolean, optional) - Enable tracking on localhost. Defaults to `false`.
```
--------------------------------
### MoneyFast Attribution Helpers
Source: https://github.com/iamcorey/analytics-script/blob/main/README.md
Helper functions to access and manage MoneyFast attribution data.
```APIDOC
## MoneyFast Attribution Helpers
### Description
MoneyFast automatically collects UTM parameters, device info, and referrer data into a cookie. These helper functions allow you to access and manage this data.
### Functions
- `getMoneyFastAttribution()`: Get raw attribution data.
- `getMoneyFastMeta()`: Get data formatted for Stripe Checkout metadata.
- `clearMoneyFastAttribution()`: Clear the attribution cookie.
### Usage
```tsx
import { getMoneyFastAttribution, getMoneyFastMeta, clearMoneyFastAttribution } from 'analytics-script';
// Get raw attribution data
const data = getMoneyFastAttribution();
// Example: { moneyfast_ref: 'google', moneyfast_campaign: 'summer', moneyfast_device: 'desktop', ... }
// Get data formatted for Stripe Checkout metadata
const meta = getMoneyFastMeta();
// Clear attribution cookie
clearMoneyFastAttribution();
```
```