Cookie-free analytics in Next.js: where the script tag goes

In the App Router it's the root layout, in the Pages Router _app or _document. Then two things that can leave the dashboard empty or thin without an error on the page: a Content Security Policy, and page changes the script never sees.

8 min read

Summarize with

In this article
  1. 1What you're adding: one script tag
  2. 2App Router: the root layout
  3. 3Pages Router: _app or _document
  4. 4Script component or plain tag
  5. 5Content Security Policy: the step people miss
  6. 6Check that it works
  7. 7Client-side navigation: test it
  8. 8A cookie-free script, but is the site?
  9. 9A short checklist

Some analytics tools for Next.js come as an npm package with a component to add. A tool that installs with one script tag needs no package at all. It needs the tag in the one file that wraps every page, an entry in your Content Security Policy if you have one, and a test that clicks past the first page.

This guide works for any tool that installs with a script tag. It covers where the tag goes in the App Router and in the Pages Router, which Next.js loading options make sense for analytics, the CSP change that quietly leaves a dashboard empty, and how to check that pageviews arrive. The Next.js details follow its own documentation, as of November 2026.

What you're adding: one script tag

Find the install snippet in your analytics tool's settings. It usually looks something like this, with your own site id or domain in it:

your tool's snippet (a placeholder)
<script
  defer
  src="https://analytics.example.com/script.js"
  data-site="YOUR_SITE_ID"
></script>

Copy it exactly and keep every attribute. A data- attribute often tells the script which site the pageviews belong to, so it has to reach the page unchanged. If the snippet also has a few lines of inline code between script tags, copy those too.

You don't need an SDK, an API key in your environment variables or a build plugin for this kind of install. The examples below use analytics.example.com and YOUR_SITE_ID as placeholders. Use the address and attributes from your own snippet.

App Router: the root layout

In the App Router, the root layout, app/layout.tsx (or .js), wraps every route. The Next.js docs load third-party scripts with the built-in next/script component, which ships with Next.js, so there's nothing to install. In the root layout, the script loads on any route, and Next.js makes sure it loads only once as visitors move between pages.

app/layout.tsx, shortened
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <Script
        src="https://analytics.example.com/script.js"
        data-site="YOUR_SITE_ID"
      />
    </html>
  );
}
  • Leave the strategy alone. The default, afterInteractive, loads the script after some of the page has hydrated, and the Next.js docs list analytics as a good fit for it. beforeInteractive is meant for critical scripts such as bot detectors and cookie consent managers. lazyOnload waits for idle time, after everything else on the page has loaded, so a visitor who leaves quickly can be missed.
  • Write the attributes as they appear in the tag. Attributes the Script component doesn't use itself, such as data-* and nonce, are passed through to the final script tag.
  • Give inline code its own Script. If your snippet has inline code, put it in a separate Script with an id. Next.js needs the id to track an inline script.
  • Use the root layout, not a nested one. A script in app/dashboard/layout.tsx is only fetched once someone opens a route under /dashboard, so visits that never get there go uncounted, and so do the pages seen before it.

Pages Router: _app or _document

Projects that use the pages directory have two places that wrap every page. Pick one of them, not both.

Option 1: pages/_app.tsx with the Script component

This is what the Next.js docs show for a script that should load on every route in the Pages Router, and the closest match to the App Router example above. The same notes about strategy and attributes apply.

pages/_app.tsx
import type { AppProps } from "next/app";
import Script from "next/script";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Script
        src="https://analytics.example.com/script.js"
        data-site="YOUR_SITE_ID"
      />
    </>
  );
}

Option 2: a plain tag in pages/_document.tsx

If you'd rather paste the tag close to how your tool printed it, put it inside <Head> in a custom document. The document is rendered on the server only, which is fine for a tag that just has to be in the HTML.

pages/_document.tsx
import { Html, Head, Main, NextScript } from "next/document";

export default function Document() {
  return (
    <Html lang="en">
      <Head>
        <script
          defer
          src="https://analytics.example.com/script.js"
          data-site="YOUR_SITE_ID"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
  • Use Head from next/document. It's not the same component as next/head. The docs keep the document's Head for head code that every page shares, and the Next.js lint rules flag a Script component placed inside next/head.
  • Keep defer. Without it the tag holds up the page while the script loads, and the no-sync-scripts rule in the Next.js lint config flags exactly that.

Script component or plain tag

Both end with the browser loading the same file. The difference is who decides when it loads.

next/scriptPlain tag in _document
Where it can goRoot layout in the App Router, or _app in the Pages RouterPages Router only, since _document doesn't exist in the App Router
When it loadsSet by the strategy prop. The default waits until the page has started to hydrateDownloaded while the HTML is parsed, and run once parsing is done because of defer
In View Page SourceNot as a script tag with the default strategy, which adds it in the browser. Look in the Elements panel insteadYes, it's in the HTML from the server

If you use a static export (output: 'export'), the placement doesn't change. Next.js still renders the root layout or the custom document into every HTML file it writes.

Content Security Policy: the step people miss

If your site sends a Content Security Policy that limits scripts, the browser blocks any script from a domain the policy doesn't list. Nothing on the page breaks and no error appears for visitors. The dashboard just stays empty.

In a Next.js project the policy usually comes from one of three places: the headers() function in next.config.js, a proxy.ts file (called middleware.ts before Next.js 16), or your host's settings. With a static export, headers() and Proxy aren't supported, so a policy there comes from the host's settings or from a <meta http-equiv="Content-Security-Policy"> tag in the root layout or the custom document.

An analytics script usually needs its domain in two directives: script-src so the script may load, and connect-src so the request that carries the pageview may leave. The Next.js CSP guide does the same for Google Analytics in its own example.

the two directives to extend, with your tool's domain
script-src 'self' https://analytics.example.com;
connect-src 'self' https://analytics.example.com;
  1. Open the deployed site with the browser's developer tools open on the Console.
  2. Look for messages about a Content Security Policy violation that name the script.
  3. Add the domain the message names to the directive it names, then redeploy and check again.

Check that it works

Don't wait a day to find out the tag is broken. Check right after you deploy:

  1. Use the production domain. Not localhost and not a preview address. Some tools ignore pageviews from hostnames you haven't added, on purpose.
  2. Turn off ad blockers for the check, or use a browser profile without extensions. Many of them stop analytics scripts.
  3. Open the Network panel and reload. Filter by your tool's domain. You should see the script load without an error, then a request that sends the pageview.
  4. Look at the Console for errors that mention the script, including CSP violations.
  5. Search the Elements panel for the script's address and confirm the tag is there once. With the Script component, View Page Source won't show the tag.
  6. Open your tool's live or real-time view, if it has one. Your visit should appear within a short time.

Ad blockers don't only matter for the test. A visitor whose blocker stops your tool's script isn't counted at all, which is one reason two tools never agree. The other reasons are in why no two analytics tools agree on your traffic.

Client-side navigation: test it

When someone follows a <Link>, Next.js changes the page without loading a new document. The script in your root layout doesn't load again either: Next.js loads it once. So it's up to the script itself to notice that the page changed. Many do, by watching the browser's History API, but it's worth testing rather than assuming.

  1. Load your home page on the production domain.
  2. Click through to two or three other pages using the site's own links.
  3. Check that each page shows up, as its own request in the Network panel and as a pageview in your tool.

If only the first page appears, look in your tool's docs for single-page apps before you trust its top pages report. Some tools also count a new pageview only when the path changes, so filters or tabs kept in the query string don't add pageviews. There's more on this in why single-page apps trip up some tools.

One page in the dashboard after five pages in the browser means the script missed the navigation, not the visitor.

A cookie-free analytics script removes one source of cookies. It doesn't make the whole site cookie-free. A Next.js project can set cookies in other places: an authentication library, a proxy.ts that stores a locale or an experiment, embedded videos, chat widgets, payment forms.

To see what your site actually sets, open the developer tools, go to Application (Storage in Firefox), clear the site data and browse a few pages. Whatever appears under Cookies, Local storage and Session storage came from somewhere. Whether you can drop a cookie banner depends on that whole list, not on the analytics tool alone. The steps are in what it takes to run a website without a cookie banner.

A short checklist

  • Copy the whole snippet, attributes and any inline code included.
  • App Router: a Script component in app/layout.tsx. Pages Router: a Script in pages/_app.tsx, or a plain tag with defer in pages/_document.tsx. One of them, once.
  • Keep the default strategy.
  • With a CSP, add the tool's domain to script-src and connect-src.
  • Check on the production domain with blockers off: Network, Console, live view.
  • Click through three pages and make sure each one is counted.
  • List what else the site stores before you decide about a cookie banner.

Lomen is one of the script-tag tools this guide is written for. Its tag carries defer, your data-site-id and the script address https://lomenanalytics.com/api/public/track.js, with no API key, package or build step, so in Next.js it goes in the root layout, _app or _document as above. With a Content Security Policy, allow https://lomenanalytics.com in both script-src and connect-src. The script counts page changes made through the History API with no extra code, a second copy of the tag for the same site does nothing, and pageviews only count from the domain you added and its subdomains, so localhost stays out of the numbers. It sets no cookies, IP addresses are never stored, and by default nothing is kept in the visitor's browser. It doesn't track custom events or funnels, so if you need to follow sign-up steps or button clicks, a broader tool is the better fit. Lomen is free during the public beta.

Numbers you can ask questions

Lomen is one cookie-free script: sources, campaigns and AI referrals on one dashboard, and an AI that answers from your own figures. Free during the beta, no credit card.