Next.js course ยท Module 8: Deployment and Production

Integration with Web Analytics

12 min read ยท
In this lesson13

In the world of web applications, understanding user behavior and measuring effectiveness is key to making sound business and technical decisions. Integrating analytics tools with a Next.js application allows tracking traffic, user behavior, conversions, and other important performance indicators.

The most commonly used analytics tools in Next.js applications include:

  1. Google Analytics - a comprehensive tool with a wide range of analytics features
  2. Vercel Analytics - native analytics for applications hosted on Vercel
  3. Plausible - privacy-friendly open-source alternative
  4. Fathom - simple and privacy-focused analytics system
  5. PostHog - all-in-one platform combining analytics, user sessions, and experimental features
  6. Mixpanel - advanced analytics with a focus on event tracking and conversion funnels
  7. Amplitude - focused on user behavior analysis and product analytics

Google Analytics 4 (GA4) integration

Google Analytics is the most popular analytics tool. Here's how to integrate GA4 with a Next.js application:

1. Google Analytics configuration

Start by creating a Google Analytics account and configuring a data stream:

  1. Go to Google Analytics
  2. Create a new account and set up a site indicator
  3. Configure a web data stream and note the measurement ID (G-XXXXXXXX)

2. Implementation in Next.js using App Router

Create a Google Analytics component:

// components/GoogleAnalytics.tsx
'use client';

import Script from 'next/script';

export default function GoogleAnalytics({ GA_MEASUREMENT_ID }: { GA_MEASUREMENT_ID: string }) {
  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_MEASUREMENT_ID}', {
              page_path: window.location.pathname,
              cookie_flags: 'SameSite=None;Secure'
            });
          `,
        }}
      />
    </>
  );
}

Then add the component to the main application layout:

// app/layout.tsx
import GoogleAnalytics from '@/components/GoogleAnalytics';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        {process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID && (
          <GoogleAnalytics GA_MEASUREMENT_ID={process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID} />
        )}
        {children}
      </body>
    </html>
  );
}

Make sure to add the environment variable to the file .env.local:

NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX

3. Tracking navigation between pages

In App Router, you should implement URL change tracking because client-side navigation does not cause a full page refresh:

// hooks/usePageTracking.ts
'use client';

import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';

export function usePageTracking() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (pathname && window.gtag) {
      let url = window.origin + pathname;
      if (searchParams.toString()) {
        url = url + '?' + searchParams.toString();
      }

      window.gtag('config', process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID!, {
        page_path: pathname,
        page_location: url,
      });
    }
  }, [pathname, searchParams]);
}

Then use this hook in a client component:

// components/PageTracker.tsx
'use client';

import { usePageTracking } from '@/hooks/usePageTracking';

export default function PageTracker() {
  usePageTracking();
  return null;
}

// app/layout.tsx
import PageTracker from '@/components/PageTracker';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        {process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID && (
          <>
            <GoogleAnalytics GA_MEASUREMENT_ID={process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID} />
            <PageTracker />
          </>
        )}
        {children}
      </body>
    </html>
  );
}

4. Custom event tracking

Create a tool for tracking custom events:

// lib/analytics.ts
'use client';

export type EventOptions = {
  category: string;
  label?: string;
  value?: number;
  nonInteraction?: boolean;
  [key: string]: any;
};

export const trackEvent = (action: string, options: EventOptions) => {
  const { category, label, value, nonInteraction = false, ...restOptions } = options;

  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('event', action, {
      event_category: category,
      event_label: label,
      value: value,
      non_interaction: nonInteraction,
      ...restOptions,
    });
  }
};

Usage in a component:

// components/SubscribeButton.tsx
'use client';

import { trackEvent } from '@/lib/analytics';

export default function SubscribeButton() {
  const handleSubscribe = () => {
    // Subscription logic...

    // Event tracking
    trackEvent('subscribe', {
      category: 'Engagement',
      label: 'Newsletter',
      value: 1,
    });
  };

  return (
    <button
      onClick={handleSubscribe}
      className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded"
    >
      Subscribe to newsletter
    </button>
  );
}

Integration with Vercel Analytics

If you host your Next.js application on Vercel, you can take advantage of Vercel's built-in analytics, which offers easy deployment and solid performance metrics.

1. Installing the @vercel/analytics package

npm install @vercel/analytics
# or
yarn add @vercel/analytics
# or
pnpm add @vercel/analytics

2. Adding the analytics provider

// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  );
}

That's all! Vercel automatically collects data on page visits and key Web Vitals metrics.

3. Custom event tracking in Vercel Analytics

// components/ContactForm.tsx
'use client';

import { track } from '@vercel/analytics';
import { useState } from 'react';

export default function ContactForm() {
  const [email, setEmail] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // Contact form logic...

    // Event tracking
    track('contact_form_submitted', { email_domain: email.split('@')[1] });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="email" className="block mb-1">Email</label>
        <input
          id="email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          required
          className="w-full px-3 py-2 border rounded"
        />
      </div>
      <button
        type="submit"
        className="bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded"
      >
        Send
      </button>
    </form>
  );
}

Integration of privacy-friendly analytics tools

With growing privacy awareness and regulations such as GDPR, many companies choose privacy-friendly analytics tools. Below you will find an example of integration with Plausible Analytics.

Integration with Plausible Analytics

// components/PlausibleAnalytics.tsx
'use client';

import Script from 'next/script';

export default function PlausibleAnalytics({ domain }: { domain: string }) {
  return (
    <Script
      strategy="afterInteractive"
      data-domain={domain}
      src="https://plausible.io/js/script.js"
    />
  );
}

// app/layout.tsx
import PlausibleAnalytics from '@/components/PlausibleAnalytics';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        {process.env.NEXT_PUBLIC_ANALYTICS_DOMAIN && (
          <PlausibleAnalytics domain={process.env.NEXT_PUBLIC_ANALYTICS_DOMAIN} />
        )}
        {children}
      </body>
    </html>
  );
}

Integration with PostHog

PostHog is a comprehensive open-source analytics platform that combines analytics, session recording, AB testing features, and more.

// app/providers.tsx
'use client';

import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect } from 'react';

if (typeof window !== 'undefined' && process.env.NEXT_PUBLIC_POSTHOG_KEY) {
  posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
    api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com',
    // Other options...
    capture_pageview: false // Disable automatic page view tracking
  });
}

export function PostHogPageview(): JSX.Element {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (pathname) {
      let url = window.origin + pathname;
      if (searchParams && searchParams.toString()) {
        url = url + `?${searchParams.toString()}`;
      }
      posthog.capture('$pageview', {
        $current_url: url,
      });
    }
  }, [pathname, searchParams]);

  return <></>;
}

export function PHProvider({ children }: { children: React.ReactNode }) {
  return (
    <PostHogProvider client={posthog}>
      <PostHogPageview />
      {children}
    </PostHogProvider>
  );
}

// app/layout.tsx
import { PHProvider } from './providers';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        <PHProvider>{children}</PHProvider>
      </body>
    </html>
  );
}

In accordance with personal data protection regulations, user consent must be obtained before starting tracking. Implementation of a simple cookie banner:

// components/CookieConsent.tsx
'use client';

import { useState, useEffect } from 'react';

export default function CookieConsent() {
  const [consent, setConsent] = useState<boolean | null>(null);

  useEffect(() => {
    // Check if the user has already given consent
    const storedConsent = localStorage.getItem('cookieConsent');
    if (storedConsent !== null) {
      setConsent(storedConsent === 'true');
    } else {
      setConsent(false); // No consent by default
    }
  }, []);

  const handleAccept = () => {
    localStorage.setItem('cookieConsent', 'true');
    setConsent(true);

    // Enable analytics
    if (window.gtag) {
      window.gtag('consent', 'update', {
        'analytics_storage': 'granted'
      });
    }
  };

  const handleReject = () => {
    localStorage.setItem('cookieConsent', 'false');
    setConsent(false);

    // Disable analytics
    if (window.gtag) {
      window.gtag('consent', 'update', {
        'analytics_storage': 'denied'
      });
    }
  };

  if (consent === null || consent === true) {
    return null; // Don't show banner if consent has been given or hasn't loaded yet
  }

  return (
    <div className="fixed bottom-0 left-0 right-0 bg-gray-100 p-4 shadow-md z-50">
      <div className="max-w-6xl mx-auto flex flex-col md:flex-row items-center justify-between">
        <div className="mb-4 md:mb-0">
          <p className="text-sm">
            This page uses cookies to analyze traffic. You can decide whether to accept cookies.
          </p>
        </div>
        <div className="flex space-x-4">
          <button
            onClick={handleReject}
            className="px-4 py-2 text-sm border border-gray-300 rounded hover:bg-gray-200"
          >
            Reject
          </button>
          <button
            onClick={handleAccept}
            className="px-4 py-2 text-sm bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Accept
          </button>
        </div>
      </div>
    </div>
  );
}

// app/layout.tsx
import CookieConsent from '@/components/CookieConsent';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="pl">
      <body>
        {children}
        <CookieConsent />
      </body>
    </html>
  );
}

Adapting Google Analytics to GDPR requirements

Modify the Google Analytics initialization to take user consent into account:

// components/GoogleAnalytics.tsx
'use client';

import Script from 'next/script';
import { useEffect } from 'react';

export default function GoogleAnalytics({ GA_MEASUREMENT_ID }: { GA_MEASUREMENT_ID: string }) {
  useEffect(() => {
    // Check the user's consent
    const consent = localStorage.getItem('cookieConsent') === 'true';

    // Update the consent state in Google Analytics
    if (window.gtag) {
      window.gtag('consent', 'update', {
        'analytics_storage': consent ? 'granted' : 'denied'
      });
    }
  }, []);

  return (
    <>
      <Script
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            // Set default consent as 'denied'
            gtag('consent', 'default', {
              'analytics_storage': 'denied'
            });

            // Configure Google Analytics
            gtag('config', '${GA_MEASUREMENT_ID}', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
    </>
  );
}

Cross-platform integration: Web, iOS, Android

For applications that run on multiple platforms, it's worth implementing consistent analytics tracking. You can use libraries such as Segment, Amplitude or Firebase Analytics, which offer SDKs for different platforms.

Example with Firebase Analytics

// lib/analytics.ts
import { initializeApp } from 'firebase/app';
import { getAnalytics, logEvent, isSupported } from 'firebase/analytics';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  // Other configuration...
};

let analytics: any = null;

export async function initAnalytics() {
  if (typeof window !== 'undefined' && await isSupported()) {
    const app = initializeApp(firebaseConfig);
    analytics = getAnalytics(app);
    return true;
  }
  return false;
}

export function trackEvent(eventName: string, eventParams?: any) {
  if (analytics) {
    logEvent(analytics, eventName, eventParams);
  }
}

// components/AnalyticsProvider.tsx
'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { initAnalytics, trackEvent } from '@/lib/analytics';

export default function AnalyticsProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    initAnalytics();
  }, []);

  useEffect(() => {
    if (pathname) {
      trackEvent('page_view', {
        page_path: pathname,
        page_search: searchParams?.toString(),
      });
    }
  }, [pathname, searchParams]);

  return <>{children}</>;
}

Measuring Web Vitals

Web Vitals metrics are key to understanding your application's performance. Next.js offers a built-in tool for reporting Web Vitals to analytics systems:

// app/layout.tsx
import { useReportWebVitals } from 'next/web-vitals';

export function WebVitals() {
  useReportWebVitals((metric) => {
    const { id, name, label, value } = metric;

    // Reporting to Google Analytics
    if (window.gtag) {
      window.gtag('event', name, {
        event_category: 'Web Vitals',
        event_label: label,
        value: Math.round(name === 'CLS' ? value * 1000 : value),
        non_interaction: true,
        metric_id: id,
      });
    }

    // Reporting to the console in the development environment
    if (process.env.NODE_ENV === 'development') {
      console.log(`Web Vital: ${name}`, metric);
    }
  });

  return null;
}

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="pl">
      <body>
        <WebVitals />
        {children}
      </body>
    </html>
  );
}

Custom analytics dashboards

Sometimes you need to visualize analytics data directly in your application. You can implement your own analytics dashboard by fetching data from the Google Analytics API or another tool:

// app/admin/analytics/page.tsx
import { google } from 'googleapis';
import { BarChart, LineChart } from '@/components/Charts';

async function getAnalyticsData() {
  try {
    // Initialize the Google Analytics client
    const auth = new google.auth.GoogleAuth({
      keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
      scopes: ['https://www.googleapis.com/auth/analytics.readonly'],
    });

    const analyticsreporting = google.analyticsreporting({
      version: 'v4',
      auth,
    });

    // Fetch the analytics data
    const response = await analyticsreporting.reports.batchGet({
      requestBody: {
        reportRequests: [
          {
            viewId: process.env.GA_VIEW_ID,
            dateRanges: [{ startDate: '30daysAgo', endDate: 'today' }],
            metrics: [{ expression: 'ga:sessions' }, { expression: 'ga:pageviews' }],
            dimensions: [{ name: 'ga:date' }],
          },
        ],
      },
    });

    // Process the data
    const report = response.data.reports[0];
    const rows = report.data.rows;

    return rows.map((row) => ({
      date: row.dimensions[0],
      sessions: parseInt(row.metrics[0].values[0], 10),
      pageviews: parseInt(row.metrics[0].values[1], 10),
    }));
  } catch (error) {
    console.error('Error during fetching analytics data:', error);
    return [];
  }
}

export default async function AnalyticsDashboard() {
  const analyticsData = await getAnalyticsData();

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold mb-6">Analytics dashboard</h1>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white p-4 rounded shadow">
          <h2 className="text-lg font-semibold mb-4">Sessions vs. page views</h2>
          <LineChart
            data={analyticsData}
            categories={['sessions', 'pageviews']}
            xKey="date"
          />
        </div>

        <div className="bg-white p-4 rounded shadow">
          <h2 className="text-lg font-semibold mb-4">Page views by day</h2>
          <BarChart
            data={analyticsData}
            category="pageviews"
            xKey="date"
          />
        </div>
      </div>
    </div>
  );
}

Testing and debugging analytics

Before deploying to production, it's worth testing the analytics integration in the development environment:

// lib/analytics.ts
export function trackEvent(eventName: string, eventParams: any = {}) {
  // In the development environment, print events to the console
  if (process.env.NODE_ENV === 'development') {
    console.log(`Analytics Event: ${eventName}`, eventParams);
    return;
  }

  // In the production environment, send to the analytics service
  if (window.gtag) {
    window.gtag('event', eventName, eventParams);
  }
}

For testing you can also use browser extensions such as Google Analytics Debugger, Tag Assistant or Facebook Pixel Helper.

Best practices

  1. Respect user privacy - always inform about the use of analytics tools and collect consent
  2. Minimize impact on performance - use the strategy afterInteractive or lazyOnload for analytics scripts
  3. Segment data - categorize events to make data easier to analyze
  4. Use multiple data sources - combine data from different tools for a fuller picture
  5. Regularly verify data - check the correctness of analytics data
  6. Analyze trends - look for patterns and anomalies in data
  7. Anonymize data - collect data in a GDPR-compliant manner

Analytics frameworks for Next.js

For more advanced needs, it's worth considering using specialized analytics frameworks for Next.js:

  1. Next-GA - simplified integration with Google Analytics
  2. Use-Analytics - a universal hook for integrating with different analytics providers
  3. React-GA - a popular library for integrating React with Google Analytics
  4. Next-Plausible - integration with the privacy-friendly tool Plausible

Summary

Web analytics is a key tool for understanding users and optimizing applications. Next.js offers many ways to integrate with various analytics tools, from Google Analytics through Vercel Analytics to more privacy-friendly alternatives such as Plausible or Fathom.

Remember that the most important thing is to collect only the data that is really needed and to do it with respect for user privacy. Good practices include obtaining consent, anonymizing data, and informing users about what data is collected and for what purpose.

Code for this lesson: App.tsx
import React, { useState, useEffect } from 'react';

// Demo: Web Analytics Integration
interface AnalyticsEvent {
  id: string;
  type: 'pageview' | 'click' | 'scroll' | 'conversion' | 'error';
  page: string;
  timestamp: string;
  data?: string;
}

interface AnalyticsMetrics {
  pageViews: number;
  uniqueVisitors: number;
  bounceRate: number;
  avgSessionDuration: number;
  topPages: { page: string; views: number }[];
}

function AnalyticsDemo() {
  const [events, setEvents] = useState<AnalyticsEvent[]>([]);
  const [metrics, setMetrics] = useState<AnalyticsMetrics>({
    pageViews: 1247,
    uniqueVisitors: 892,
    bounceRate: 34.2,
    avgSessionDuration: 245,
    topPages: [
      { page: '/', views: 456 },
      { page: '/blog', views: 312 },
      { page: '/products', views: 278 },
      { page: '/about', views: 201 },
    ],
  });
  const [activeProvider, setActiveProvider] = useState<'ga4' | 'plausible' | 'custom'>('ga4');
  const [isTracking, setIsTracking] = useState(true);

  const providers = [
    { id: 'ga4' as const, name: 'Google Analytics 4', color: '#f59e0b' },
    { id: 'plausible' as const, name: 'Plausible', color: '#10b981' },
    { id: 'custom' as const, name: 'Custom Analytics', color: '#8b5cf6' },
  ];

  const trackEvent = (type: AnalyticsEvent['type'], page: string, data?: string) => {
    if (!isTracking) return;
    const event: AnalyticsEvent = {
      id: Math.random().toString(36).substr(2, 6),
      type, page, data,
      timestamp: new Date().toLocaleTimeString(),
    };
    setEvents(prev => [event, ...prev.slice(0, 19)]);
    if (type === 'pageview') {
      setMetrics(prev => ({ ...prev, pageViews: prev.pageViews + 1 }));
    }
  };

  const eventColors: Record<string, string> = {
    pageview: '#3b82f6', click: '#10b981', scroll: '#f59e0b', conversion: '#8b5cf6', error: '#ef4444',
  };

  const codeSnippets: Record<string, string> = {
    ga4: "// app/layout.tsx\nimport { GoogleAnalytics } from '@next/third-parties/google';\n\nexport default function RootLayout({ children }) {\n  return (\n    <html>\n      <body>{children}</body>\n      <GoogleAnalytics gaId=\"G-XXXXXXX\" />\n    </html>\n  );\n}",
    plausible: "// app/layout.tsx\nimport Script from 'next/script';\n\nexport default function RootLayout({ children }) {\n  return (\n    <html>\n      <body>\n        {children}\n        <Script\n          defer\n          data-domain=\"yourdomain.com\"\n          src=\"https://plausible.io/js/script.js\"\n        />\n      </body>\n    </html>\n  );\n}",
    custom: "// lib/analytics.ts\nexport function trackPageView(url: string) {\n  fetch('/api/analytics', {\n    method: 'POST',\n    body: JSON.stringify({ type: 'pageview', url, timestamp: Date.now() }),\n  });\n}\n\n// app/layout.tsx - use in useEffect\nuseEffect(() => {\n  trackPageView(pathname);\n}, [pathname]);",
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>Web Analytics Dashboard</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Analytics integration in Next.js</p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '16px', marginBottom: '24px' }}>
        {[
          { label: 'Page Views', value: metrics.pageViews.toLocaleString(), color: '#3b82f6' },
          { label: 'Unique Visitors', value: metrics.uniqueVisitors.toLocaleString(), color: '#10b981' },
          { label: 'Bounce Rate', value: metrics.bounceRate + '%', color: '#f59e0b' },
          { label: 'Avg Session', value: Math.floor(metrics.avgSessionDuration / 60) + 'm ' + (metrics.avgSessionDuration % 60) + 's', color: '#8b5cf6' },
        ].map(m => (
          <div key={m.label} style={{ background: '#1a1a2e', padding: '16px', borderRadius: '12px', border: '1px solid #333', textAlign: 'center' }}>
            <div style={{ fontSize: '28px', fontWeight: 'bold', color: m.color }}>{m.value}</div>
            <div style={{ fontSize: '13px', color: '#8892b0', marginTop: '4px' }}>{m.label}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '20px' }}>
        {providers.map(p => (
          <button key={p.id} onClick={() => setActiveProvider(p.id)} style={{
            padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer',
            background: activeProvider === p.id ? p.color : '#1a1a2e', color: activeProvider === p.id ? '#fff' : '#8892b0', fontWeight: 'bold',
          }}>{p.name}</button>
        ))}
        <button onClick={() => setIsTracking(!isTracking)} style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', cursor: 'pointer', background: isTracking ? '#10b981' : '#ef4444', color: '#fff', marginLeft: 'auto' }}>
          {isTracking ? 'Tracking ON' : 'Tracking OFF'}
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px', marginBottom: '24px' }}>
        <div>
          <h3 style={{ color: '#64ffda', fontSize: '16px' }}>Simulate events</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
            {[
              { type: 'pageview' as const, label: 'Page View', page: '/home' },
              { type: 'click' as const, label: 'Button Click', page: '/cta' },
              { type: 'scroll' as const, label: 'Scroll 50%', page: '/blog' },
              { type: 'conversion' as const, label: 'Conversion', page: '/checkout' },
              { type: 'error' as const, label: 'JS Error', page: '/app' },
            ].map(e => (
              <button key={e.type} onClick={() => trackEvent(e.type, e.page, e.label)} style={{
                padding: '10px', borderRadius: '8px', border: '1px solid ' + eventColors[e.type], background: eventColors[e.type] + '20', color: eventColors[e.type], cursor: 'pointer',
              }}>{e.label}</button>
            ))}
          </div>
        </div>
        <div>
          <h3 style={{ color: '#64ffda', fontSize: '16px' }}>Event Log</h3>
          <div style={{ maxHeight: '200px', overflow: 'auto', background: '#1a1a2e', borderRadius: '8px', padding: '12px', border: '1px solid #333' }}>
            {events.map(e => (
              <div key={e.id} style={{ fontSize: '12px', padding: '4px 0', borderBottom: '1px solid #222', display: 'flex', gap: '8px' }}>
                <span style={{ color: eventColors[e.type], minWidth: '80px' }}>{e.type}</span>
                <span style={{ color: '#64ffda' }}>{e.page}</span>
                <span style={{ color: '#555', marginLeft: 'auto' }}>{e.timestamp}</span>
              </div>
            ))}
            {events.length === 0 && <p style={{ color: '#555', margin: 0 }}>No events</p>}
          </div>
        </div>
      </div>

      <div style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', border: '1px solid #333' }}>
        <h3 style={{ color: '#f59e0b', fontSize: '14px', marginTop: 0 }}>Integration code ({providers.find(p => p.id === activeProvider)?.name}):</h3>
        <pre style={{ fontSize: '12px', color: '#e0e0e0', margin: 0, overflow: 'auto', whiteSpace: 'pre-wrap' }}>{codeSnippets[activeProvider]}</pre>
      </div>
    </div>
  );
}

export default AnalyticsDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Core Web Vitals include:

Hands-on tasks in the game

  • Code editor

    Create a control panel with Web Vitals monitoring

  • Click in order

    Arrange the syntax of the reportWebVitals function in Next.js

  • Code editor

    Implement a dashboard optimized for performance

  1. Coding taskPractice: Monitoring Web Vitals
  2. Click in orderSequence: export โ†’ function โ†’ reportWebVitals
  3. QuestionCore Web Vitals include:
  4. Coding taskPractice: Performance-Optimized Dashboard

Useful articles