← Back to articles

How to Add Analytics to Next.js (2026 Guide)

You've built your Next.js app. Now you need to know who's using it and how. Here's how to add analytics — from the simplest one-liner to full product analytics.

Your Options at a Glance

ToolTypePrivacyPriceSetup
Vercel AnalyticsWeb vitals + trafficPrivacy-friendlyFree - $14/moOne line
PostHogProduct analytics (full)Self-host optionFree - $450+/moSDK
PlausibleTraffic analyticsPrivacy-first$9/moScript tag
UmamiTraffic analyticsSelf-host (free)Free - $9/moScript tag
Google AnalyticsTraffic + marketingNot privacy-friendlyFreeScript tag
MixpanelProduct analyticsCloudFree - $28+/moSDK
FathomTraffic analyticsPrivacy-first$14/moScript tag

Option 1: Vercel Analytics (Simplest)

If you're on Vercel, this is the fastest setup in existence.

Setup

npm install @vercel/analytics @vercel/speed-insights
// app/layout.tsx
import { Analytics } from '@vercel/analytics/react';
import { SpeedInsights } from '@vercel/speed-insights/next';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
        <SpeedInsights />
      </body>
    </html>
  );
}

Done. You get page views, unique visitors, referrers, and Core Web Vitals.

What You Get

  • Page views and unique visitors
  • Referrer tracking
  • Country/device breakdown
  • Core Web Vitals (LCP, FID, CLS, TTFB)
  • Real user performance monitoring

What You Don't Get

  • Custom events (limited on free plan)
  • User identification
  • Funnels, cohorts, or retention analysis
  • Session recordings or heatmaps

Pricing

  • Free: 2,500 events/month
  • Pro: Included with Vercel Pro ($20/month for team)

Best For

Simple traffic analytics with zero configuration. Perfect if you just want to know how many people visit your site.

Option 2: PostHog (Most Complete)

PostHog is the most comprehensive open-source analytics platform. It covers everything: analytics, session recordings, feature flags, A/B tests, and surveys.

Setup

npm install posthog-js
// app/providers.tsx
'use client';
import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { useEffect } from 'react';

export function PHProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
      api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
      capture_pageview: false, // We handle manually for Next.js
    });
  }, []);

  return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}
// app/layout.tsx
import { PHProvider } from './providers';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <PHProvider>{children}</PHProvider>
      </body>
    </html>
  );
}
// components/PostHogPageView.tsx
'use client';
import { usePathname, useSearchParams } from 'next/navigation';
import { usePostHog } from 'posthog-js/react';
import { useEffect } from 'react';

export function PostHogPageView() {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const posthog = usePostHog();

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

  return null;
}

Custom Events

import { usePostHog } from 'posthog-js/react';

function SignupButton() {
  const posthog = usePostHog();
  
  return (
    <button onClick={() => {
      posthog.capture('signup_clicked', { plan: 'pro', source: 'pricing_page' });
    }}>
      Sign Up
    </button>
  );
}

What You Get

  • Page views and traffic analytics
  • Custom event tracking
  • Session recordings (watch users interact)
  • Heatmaps
  • Feature flags and A/B testing
  • Funnels, cohorts, and retention
  • Surveys
  • Self-hosting option

Pricing

  • Free: 1M events/month, 5K recordings/month
  • Paid: Based on usage (starts cheap, scales with volume)

Best For

SaaS products that need full product analytics. The "all-in-one" choice.

Option 3: Plausible (Privacy-First)

Plausible is a privacy-friendly Google Analytics alternative. No cookies, GDPR-compliant by default, lightweight script.

Setup

// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Script
          defer
          data-domain="yourdomain.com"
          src="https://plausible.io/js/script.js"
        />
      </body>
    </html>
  );
}

Custom Events

// Track custom events
function handleSignup() {
  window.plausible?.('Signup', { props: { plan: 'pro' } });
}

What You Get

  • Page views, visitors, bounce rate
  • Referrer and UTM tracking
  • Country/device/browser breakdown
  • Goal/event tracking
  • No cookie banner required (GDPR-compliant)
  • 1KB script (vs Google Analytics' 45KB)

Pricing

  • Cloud: From $9/month (10K pageviews)
  • Self-hosted: Free (Community Edition)

Best For

Content sites, blogs, and landing pages where privacy matters and you don't need product analytics.

Option 4: Umami (Self-Hosted Free)

Umami is the open-source alternative to Plausible. Self-host for free, or use their cloud service.

Setup (Cloud)

// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Script
          defer
          src="https://cloud.umami.is/script.js"
          data-website-id="your-website-id"
        />
      </body>
    </html>
  );
}

Self-Hosting

# Deploy to Vercel, Railway, or any Node.js host
git clone https://github.com/umami-software/umami.git
# Configure DATABASE_URL and deploy

Pricing

  • Self-hosted: Free forever
  • Cloud: From $9/month

Best For

Developers who want privacy-friendly analytics without paying. Self-hosting on your existing infrastructure.

Option 5: Google Analytics 4 (Most Features, Least Privacy)

If you need marketing attribution, Google Ads integration, or your marketing team demands it.

Setup

// app/layout.tsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Script
          src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_ID}`}
          strategy="afterInteractive"
        />
        <Script id="google-analytics" strategy="afterInteractive">
          {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('consent', 'default', {
              analytics_storage: 'denied',
              ad_storage: 'denied',
            });
            gtag('config', '${process.env.NEXT_PUBLIC_GA_ID}');
          `}
        </Script>
      </body>
    </html>
  );
}

Note: GA4 requires a cookie consent banner in the EU. Consider using a consent management platform.

Best For

Marketing teams that need Google Ads attribution, audience building, and the Google ecosystem.

Choosing the Right Analytics

For a Blog / Content Site

Plausible or Umami. Lightweight, privacy-friendly, no cookie banner needed. You just need pageviews and referrers.

For a SaaS Product

PostHog. You need custom events, funnels, session recordings, and feature flags. PostHog covers all of it.

For a Landing Page

Vercel Analytics (if on Vercel) or Plausible. Simple traffic numbers to validate your marketing.

For an E-commerce Store

Google Analytics 4 for marketing attribution + PostHog for product analytics. You need both marketing and product data.

For Maximum Privacy

Umami (self-hosted). Data stays on your server. No third parties. GDPR, CCPA, and PECR compliant by design.

Performance Impact

ToolScript SizeImpact on Core Web Vitals
Vercel Analytics~1KBNegligible
Plausible~1KBNegligible
Umami~2KBNegligible
PostHog~20KBMinimal (lazy loads)
Google Analytics~45KBModerate

Privacy-friendly tools are dramatically lighter than Google Analytics. If Core Web Vitals matter to you (they should for SEO), prefer lighter options.

FAQ

Do I need a cookie banner?

No for Plausible, Umami, Fathom, and Vercel Analytics — they don't use cookies. Yes for Google Analytics, PostHog (unless configured cookieless), and Mixpanel in the EU.

Can I use multiple analytics tools?

Yes, and many teams do. Common combo: Plausible for traffic (simple, fast) + PostHog for product analytics (detailed, events).

Will analytics slow down my Next.js app?

Minimal tools (Plausible, Umami, Vercel Analytics) have virtually zero performance impact. Heavier tools (GA4, PostHog) should use strategy="afterInteractive" or lazy loading.

What about server-side analytics?

You can track server-side events with PostHog, Mixpanel, or GA4's Measurement Protocol. Useful for tracking API usage, background jobs, or events that don't involve the browser.

The Verdict

  • Just want traffic numbers? → Vercel Analytics (if on Vercel) or Plausible
  • Building a SaaS product? → PostHog
  • Privacy is non-negotiable? → Umami (self-hosted)
  • Marketing team demands it? → Google Analytics 4
  • Want everything? → PostHog + Plausible (product analytics + simple traffic dashboard)

For most Next.js developers in 2026: start with Vercel Analytics (free, one line of code), then add PostHog when you need product analytics.

Get AI tool guides in your inbox

Weekly deep-dives on the best AI coding tools, automation platforms, and productivity software.