Add privacy-friendly analytics to Next.js

How-to · Updated 24 November 2026

TL;DR

Add Plausible or Umami in app/layout.tsx with next/script. Plausible's current snippet is a per-site file at plausible.io/js/pa-XXXXX.js plus plausible.init(). Umami needs data-website-id on script.js. Both can count visits without an analytics cookie. Compare hosts on the Plausible alternatives list before you pick one.

The steps below cover custom events, App Router navigations, a first-party rewrite, and localhost. Snippet attributes match the vendor docs as of 24 November 2026. This page is not legal advice.

License
$59 once
Refund
7-day no-questions refund
Stack
Next.js 16, shadcn/ui, Recharts, Postgres, Drizzle, Clerk, optional Stripe

On this page

What does privacy-friendly analytics mean in practice?

Privacy-friendly, cookieless analytics counts pageviews and a few events without setting an analytics cookie and without a cross-site profile.

Plausible's self-hosted page says the product uses no cookies and collects no personal data. The same page says no consent banner is required. Umami's pricing FAQ says Umami does not use cookies, does not collect personal data, and does not track people across websites. This site recorded that FAQ on 23 November 2026. Those are vendor claims. Copying them into your privacy notice is a legal choice, and this guide does not make it for you.

A cookie is a name and value the browser stores and sends back. Cookieless means the tracker does not use that jar. Umami's distinct-id docs say Umami does not use cookies to tell apart people who share an IP and a browser.

The request can still carry the page URL, title, referrer, language, and screen size. Umami's tracker functions page lists those, plus hostname and the website id, as the default pageview properties.

Plausible strips query parameters except ref, source, utm_source, utm_medium, utm_campaign, utm_content, and utm_term. A token in another query key is dropped from the page report. The path can still contain an email if you put one there. Do not put one there.

A consent banner is not a property of the script. Whether you need one depends on the country you serve, the purpose of the measurement, and what the request actually contains. The cookieless analytics and GDPR cookie banner guide separates ePrivacy storage from a GDPR lawful basis. It also lists when ads, replay, or a localStorage id still leave a banner in place. If you later call umami.identify() with an email, or send a user id as a Plausible property, you have left the anonymous pageview. Read the notice again. Get advice for that setup.

localStorage is not a cookie. Data Lighthouse stores a visitor id there. That is a different privacy choice than Plausible or Umami, and it is named here so the template is not described as cookieless.

If you are still choosing a product, start with the Plausible alternatives list of six free and hosted options. That page dates its prices to 23 November 2026. The Umami vs Plausible comparison is the head-to-head on price, hosting, and privacy. The Fathom Analytics alternatives page is the same kind of list when you want a short hosted dashboard. The Umami alternatives page is the longer list when Umami is the tool you might leave.

How do you add Plausible to the Next.js App Router?

Render next/script from app/layout.tsx. Plausible's current snippet has two parts: an async script at https://plausible.io/js/pa-XXXXX.js, and an inline queue that calls plausible.init().

The XXXXX segment is unique per site. Copy it from Site installation in the site settings. There is no data-domain attribute on this snippet.

Older tutorials load script.js with data-domain, or script.local.js for localhost. Plausible's script update guide says the October 2025 script replaced those attributes and file suffixes. Plausible replaced data-api with the endpoint option on plausible.init().

Snippet from Plausible's proxy guides
<script async src="https://plausible.io/js/pa-XXXXX.js"></script>
<script>
  window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
  plausible.init()
</script>

beforeInteractive is allowed in the root layout, so the queue exists before the file runs. afterInteractiveloads the file after hydration. Plausible's Next.js page documents the next-plausible package instead of this tag. The package provider takes the same pa- URL. This guide uses next/script, which is also what Umami asks for.

app/layout.tsx
import Script from "next/script"

const plausibleSrc = process.env.NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL

const plausibleQueue = `
window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
plausible.init()
`

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {plausibleSrc ? (
          <>
            <Script id="plausible-queue" strategy="beforeInteractive">
              {plausibleQueue}
            </Script>
            <Script async src={plausibleSrc} strategy="afterInteractive" />
          </>
        ) : null}
        {children}
      </body>
    </html>
  )
}

Set NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL to the full pa- URL. The value is public. It is in the HTML of every page. Omit the scripts when the variable is empty so a preview deploy does not request a placeholder file.

How do you add Umami to the Next.js App Router?

Add next/script with defer, the script URL, and data-website-id. Umami's collect-data page says to use that component instead of a plain script tag.

The bypass guide uses https://cloud.umami.is/script.js for Cloud. A self-hosted instance uses script.json that instance. The website id is the UUID on the website's tracking code screen.

data-domains is a comma-separated list matched against window.location.hostname. Include both the apex and www if you serve both. Localhost does not match, so dev traffic stays out. data-exclude-search="true" drops query strings, which is where emails and tokens usually leak.

app/layout.tsx
import Script from "next/script"

const umamiSrc = process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL
const umamiWebsiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {umamiSrc && umamiWebsiteId ? (
          <Script
            defer
            src={umamiSrc}
            strategy="afterInteractive"
            data-website-id={umamiWebsiteId}
            data-domains="example.com,www.example.com"
            data-exclude-search="true"
          />
        ) : null}
        {children}
      </body>
    </html>
  )
}

NEXT_PUBLIC_UMAMI_SCRIPT_URL and NEXT_PUBLIC_UMAMI_WEBSITE_ID both end up in the client bundle. The website id is already visible in the page source. Treat them as config, not as secrets.

.env.local
NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL=https://plausible.io/js/pa-XXXXX.js
NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://cloud.umami.is/script.js
NEXT_PUBLIC_UMAMI_WEBSITE_ID=your-website-uuid

The two installs side by side:

JobPlausibleUmami
Scriptasync pa-XXXXX.js plus plausible.init()defer script.js plus data-website-id
Custom eventplausible('Signup')umami.track('signup-button')
Client navigationshistory.pushState by defaultAutomatic, per the collect-data page
Skip localhostcaptureOnLocalhost stays falsedata-domains lists production hosts
First-party proxy/js/script.js and /api/event/stats.js and /api/send

How do you send custom events?

Call plausible('Signup'). The string is the goal name. The optional second argument accepts props, callback, revenue, and interactive.

The docs example is plausible('Download', { props: { method: 'HTTP' } }). Set interactive: false when the event should not affect bounce rate. Plausible documents the revenue object on the ecommerce page.

Sending the event is not enough. Create a custom event goal in the site settings with the same name, including capitals and spaces. Until you do, Plausible stores the hit and the dashboard shows nothing.

The no-JavaScript option is a class: plausible-event-name=Button+Click. The plus sign is a space in the goal name, so the goal is Button Click. Use one method on a control. A class plus a click handler can record the goal twice.

Umami's tracker function page documents umami.track('signup-button') and umami.track('signup-button', { plan: 'pro' }). Numbers keep at most four digits after the decimal. Strings are capped at 500 characters. An object keeps at most 50 properties.

umami.identify('unique_id') attaches a distinct id to the session. The distinct-id docs say to use an internal id or a hash, not an email, and they cap the script attribute at 50 characters. An email in session data is a personal-data decision. Skip it for a cookieless pageview setup.

components/signup-buttons.tsx
"use client"

type PlausibleOptions = {
  callback?: (result?: { status?: number; error?: unknown } | null) => void
  props?: Record<string, string>
  interactive?: boolean
}

declare global {
  interface Window {
    plausible?: (eventName: string, options?: PlausibleOptions) => void
    umami?: {
      track: (
        event?:
          | string
          | Record<string, unknown>
          | ((props: Record<string, unknown>) => Record<string, unknown>),
        data?: Record<string, unknown>,
      ) => void
    }
  }
}

export function PlausibleSignupButton() {
  return (
    <button
      type="button"
      onClick={() => {
        window.plausible?.("Signup", { props: { plan: "pro" } })
      }}
    >
      Start trial
    </button>
  )
}

export function UmamiSignupButton() {
  return (
    <button
      type="button"
      onClick={() => {
        window.umami?.track("signup-button", { plan: "pro" })
      }}
    >
      Start trial
    </button>
  )
}

How do you track App Router route changes?

Plausible's autoCapturePageviews option defaults to true. The script listens for history.pushState. The App Router uses that API for client navigations, so the default is the setup to try first.

Umami's collect-data page says single-page navigations are tracked with no extra configuration. Click an in-app link and look for a second event request before you add a manual hook.

If that second request never appears, turn automatic capture off and send the pageview yourself. For Plausible, set autoCapturePageviews: false and call plausible('pageview') when usePathname() changes. The docs say every pageview call counts, even on the same URL. Leave the listener on and you will double count.

plausible.init, manual mode only
plausible.init({ autoCapturePageviews: false })
components/plausible-manual-pageviews.tsx
"use client"

import { usePathname } from "next/navigation"
import { useEffect } from "react"

export function PlausibleManualPageviews() {
  const pathname = usePathname()

  useEffect(() => {
    window.plausible?.("pageview")
  }, [pathname])

  return null
}

For Umami, set data-auto-pageview="false". That keeps the rest of the tracker. data-auto-track="false" disables initialization entirely, so use it only when you will send every hit yourself.

Call umami.track() with a function when you want the default properties and a new url. Passing only a path object drops hostname, referrer, and the website id.

components/umami-manual-pageviews.tsx
"use client"

import { usePathname } from "next/navigation"
import { useEffect } from "react"

export function UmamiManualPageviews() {
  const pathname = usePathname()

  useEffect(() => {
    window.umami?.track((props: Record<string, unknown>) => ({
      ...props,
      url: pathname,
    }))
  }, [pathname])

  return null
}

Mount those components only in the manual mode. usePathname() does not include the query string. With data-exclude-search set, that matches what you want recorded.

How do you proxy the script past ad blockers?

Ad blockers often block the vendor hostname. A rewrite serves the script and the event POST from your domain. The payload does not change. Only the host the browser talks to changes.

Plausible's Netlify and Apache proxy guides rewrite a path such as /js/script.js to https://plausible.io/js/pa-XXXXX.js, and /api/event to https://plausible.io/api/event. The page then loads /js/script.js and calls plausible.init with endpoint: "/api/event".

next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/js/script.js",
        destination: "https://plausible.io/js/pa-XXXXX.js",
      },
      {
        source: "/api/event",
        destination: "https://plausible.io/api/event",
      },
    ]
  },
}

export default nextConfig
plausible.init for the proxied endpoint
plausible.init({ endpoint: "/api/event" })

Umami's bypass page says a Next.js app can use rewrites. The server example on that page proxies /stats.js to https://cloud.umami.is/script.js and POST /api/send to https://gateway.umami.is/api/send. Set data-host-url to your origin so the script posts to your /api/send.

next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/stats.js",
        destination: "https://cloud.umami.is/script.js",
      },
      {
        source: "/api/send",
        destination: "https://gateway.umami.is/api/send",
      },
    ]
  },
}

export default nextConfig
Proxied Umami script
<Script
  defer
  src="/stats.js"
  strategy="afterInteractive"
  data-website-id={process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID}
  data-host-url="https://example.com"
  data-domains="example.com,www.example.com"
/>

A self-hosted Umami instance uses that instance's script.js and /api/send, not the Cloud hosts. TRACKER_SCRIPT_NAME and COLLECT_API_ENDPOINT rename those paths on the Umami server. The tracker then calls the new names.

An App Router route.ts on the same path wins over the rewrite. Pick paths that have no route file. If middleware sends anonymous /api requests to sign-in, exempt the event path or the beacon gets a redirect instead of a 202.

How do you exclude localhost and check that it works?

Plausible's captureOnLocalhost option defaults to false. Localhost hits are ignored until you set it true. Turn it on only while you are checking the install, then remove it.

Temporary localhost capture
plausible.init({ captureOnLocalhost: true })

The exclude page also blocks full IP addresses, up to 30, with IPv4 and IPv6 entered separately. It can block countries and page paths, and it can allow a hostname list. The same page documents a localStorage flag for browsers whose IP changes. Use the steps in that section for the flag name.

Umami skips any hostname outside data-domains. Remove that attribute, or add localhost, only for a local check.

Then confirm the wire, not the marketing label:

  1. Open the page. The script request should return HTTP 200.
  2. Find the event POST. Plausible's Netlify proxy guide expects HTTP 202 on /api/event.
  3. A response header x-plausible-dropped: 1 means Plausible received the hit and dropped it. The custom-event docs name localhost, and a staging hostname that is not on the site, as common causes.
  4. Click an in-app link. A second pageview should fire without a full reload.
  5. Trigger the custom event. In Plausible, add the matching goal or the count stays hidden. In Umami, the event name should show after the POST succeeds.
  6. Turn the dev overrides off and reload localhost. That hit should be absent.

What does self-hosting Umami or Plausible CE take?

Hosted Plausible and Umami Cloud run the collector for you. Self-hosting moves the database, the upgrades, and the backups onto a server you operate. The snippet in your Next.js app then points at that server instead of the vendor host.

Umami on Postgres

Umami's install page requires Node.js 20.19 or newer, with 22 LTS recommended, and PostgreSQL 12.14 or newer. You set DATABASE_URL and APP_SECRET. Generate the secret with openssl rand -hex 32.

Docker Compose ships the app and PostgreSQL. Create the .env file first, then run docker compose up -d. The app listens on port 3000. The first login is username admin and password umami. Since v3.5.0 you must change that password before the app will continue.

The prebuilt image is docker.umami.is/umami-software/umami:latest. You bring your own database for that image. The install page also lists a source build and a third-party Helm chart. It does not list Vercel.

A Supabase URL can be DATABASE_URL because the requirement is PostgreSQL. Putting the Umami process on Vercel is outside that install page. You still own APP_SECRET, the admin password, upgrades, and backups. The install page recommends UTC on the database so timestamps do not shift with the server timezone.

Docker Compose, Vercel with Supabase or Neon, the Next.js rewrite, upgrades, and backups are in the self-host Umami guide.

The Plausible alternatives pagerecords Umami's GitHub license metadata as MIT on 23 November 2026. The same check lists Cloud Hobby at $0 for 100,000 events. It lists email reports and the streaming API as Cloud features, outside the self-hosted app. The nine Umami alternatives, including free self-host picks re-reads the Cloud limits, including the $200 Business plan for replay.

Plausible Community Edition on Docker

Plausible CE is AGPLv3 or any later version. There is no fee to Plausible. You pay for the server. The self-hosted page says CE is a twice-a-year release, while Cloud ships updates through the week.

Funnels, user journeys, ecommerce revenue goals, SSO, and the sites API are cloud-only. CE bot filtering uses the User-Agent and referrer-spam domains. It does not use the cloud list of data-center ranges. Security fixes protect your instance only after you apply the release.

The Community Edition README tells you to clone the v3.2.2 branch. Prerequisites on that README: Docker, Docker Compose, a CPU with SSE 4.2 or NEON, and at least 2 GB of RAM. The RAM note is for ClickHouse and Plausible.

The v3.2.2 compose.yml runs postgres:16-alpine, clickhouse/clickhouse-server:24.12-alpine, and ghcr.io/plausible/community-edition:v3.2.2. You set BASE_URL and SECRET_KEY_BASE. The README asks for at least 64 bytes and shows openssl rand -base64 48. Then docker compose up -d.

That compose file also has optional IP geolocation settings, including a MaxMind key. Turning those on means the server sees an address long enough to look up a place. Read the configuration wiki before you enable them.

Umami is the smaller stack: one app and Postgres. Plausible CE adds ClickHouse, the 2 GB note, and a CPU instruction requirement, and it keeps the Plausible dashboard while leaving several cloud reports out. Neither install replaces backups. The Umami vs Plausible page stays the product comparison. This section is only the install shape.

When do pageviews stop being enough?

A pageview answers which URL was opened, from which referrer, on which day. It does not answer which of those visits became a paid Stripe subscription.

Plausible Cloud can attach revenue to a custom event. Community Edition does not include ecommerce revenue goals. Umami's Cloud table, on the 23 November 2026 check, lists revenue. Joining that number to your coupon rules and to annual plans is still a billing problem. The pageview tool does not own your Stripe account. The guide to tracking Stripe revenue after Checkout shows the success-page call, the webhook limit, and where that goal stops.

Data Lighthouse is a Next.js template for that next report. You host it. The license is $59 once. The pricing page also shows $99 as a compare-at price. Optional Stripe cards show revenue for 7, 14, or 30 days from succeeded charges. Refunds are not subtracted. MRR counts subscriptions with status active, normalized to one month. ARR is that MRR times 12. Revenue per visitor uses distinct visitors in Postgres for the same window.

The overview does not compute churn. The tracker stores a visitor id in localStorage. It is not a Plausible clone and it does not import Plausible history. Read the self-hosted Next.js analytics dashboard template page for the stack: shadcn/ui, Drizzle on Postgres, Clerk, and optional Stripe. The guide to building that dashboard yourself walks the ingest route, the session table, and the chart if you would rather write it.

The live demo renders sample data. It does not call Stripe.Pricing is the license page. Checkout is $59 once, with GitHub sign-in before Polar payment so the buyer can be invited to the private repository.

7-day no-questions refund. If the template is not a fit, request it within 7 days through the purchase contact on the contact page.

Privacy analytics FAQ

Short answers for the App Router install, the proxy, localhost, and the point where pageviews stop.

How do I add Plausible to a Next.js App Router app?

Add next/script in app/layout.tsx. Load the per-site file https://plausible.io/js/pa-XXXXX.js and run the inline queue that calls plausible.init(). Copy that URL from Site installation in the site settings. The October 2025 snippet does not use a data-domain attribute. Set NEXT_PUBLIC_PLAUSIBLE_SCRIPT_URL to the pa- URL. It is public, because it ships in the HTML.

How do I add Umami to Next.js?

Add next/script with defer, the script URL, and data-website-id. Umami's collect-data page says to use next/script instead of a plain script tag. Cloud's bypass guide uses https://cloud.umami.is/script.js. The website id is the UUID on the tracking code screen. Put it in NEXT_PUBLIC_UMAMI_WEBSITE_ID. Set data-domains to your production hostnames so localhost does not match.

Do cookieless analytics need a consent banner?

This page is not legal advice. Plausible's self-hosted page says the product uses no cookies, collects no personal data, and does not require a consent banner. A banner is a legal control, not a script feature. The request can still carry the URL, referrer, language, and screen size. If you later send an email or a user id, read the notice again and get advice for your jurisdiction.

How do I proxy Plausible or Umami so ad blockers miss the script?

Add rewrites in next.config. Plausible's proxy guides map /js/script.js to https://plausible.io/js/pa-XXXXX.js and /api/event to https://plausible.io/api/event. Then call plausible.init({ endpoint: '/api/event' }). Umami's bypass page points Next.js at rewrites. Their server example maps /stats.js to https://cloud.umami.is/script.js and /api/send to https://gateway.umami.is/api/send, with data-host-url set to your origin.

Why does localhost not show up in Plausible or Umami?

Plausible's captureOnLocalhost option defaults to false, so dev traffic is ignored until you set it true. Umami matches data-domains against window.location.hostname. localhost fails that match. Plausible received the hit and then dropped it when the response includes x-plausible-dropped: 1. The custom-event docs name localhost, and a hostname that is not on the site, as common causes.

When should I use a dashboard template instead of Plausible or Umami?

Pageviews answer which URL was opened. They do not join that visit to a Stripe charge or to your MRR rules. Data Lighthouse is a Next.js template you host. The license is $59 once. Optional Stripe cards show succeeded-charge revenue, MRR from active subscriptions, ARR as that MRR times 12, and revenue per visitor. Refunds are not subtracted. The overview does not compute churn. The tracker stores a visitor id in localStorage, which is a different choice than a cookieless script. The sample dashboard is at https://datalighthouse.dev/demo and pricing is at https://datalighthouse.dev/pricing.

Sources