Antlytics logoAntlytics

Next.js App Router

Add the snippet once in your root layout so it runs on every route without duplication.

Use the same YOUR_TRACKING_ID and ingest URL as in Quick start. Replace the example host below if your Antlytics app runs on a different origin.

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

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script id="antlytics" strategy="afterInteractive">{
          `(function(){
  var t="YOUR_TRACKING_ID",
      u="https://www.antlytics.com/api/ingest/pageview",
      k="ant_sid";
  function sid(){try{var s=sessionStorage.getItem(k);if(s)return s;s=crypto.randomUUID();sessionStorage.setItem(k,s);return s;}catch(e){return crypto.randomUUID();}}
  function utm(){try{var p=new URLSearchParams(location.search),o={};["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(function(k){var v=p.get(k);if(v)o[k]=v;});return o;}catch(e){return {};}}
  function send(){fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},keepalive:true,body:JSON.stringify(Object.assign({tracking_id:t,pathname:location.pathname,referrer:document.referrer||undefined,session_id:sid()},utm()))});}
  send();window.addEventListener("popstate",send);
})()`
        }</Script>
      </body>
    </html>
  )
}

Prefer copying the exact string from Settings → Tracking Snippet so it never drifts from the live generator.

Something missing? Get in touch and we will update these docs.