Integrate Umami Analytics into Next.js App Router

A simple step-by-step guide to integrating Umami Analytics with Next.js App Router.
Publish date: December 6, 2024·Published in Blog

Create a new component:

import Script from "next/script"

export const UmamiAnalytics = () => {
  const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID
  if (!websiteId) {
    return <></>
  }
  return <Script async src="https://cloud.umami.is/script.js" data-website-id={websiteId} />
}

Use the component in the root layout (e.g. src/app/layout.tsx or /app/layout.tsx):

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <div>{children}</div>
        <UmamiAnalytics />
      </body>
    </html>
  )
}

Set the environment variable. For example in an env file:

# Umami website ID from https://cloud.umami.is/settings/websites
NEXT_PUBLIC_UMAMI_WEBSITE_ID=<website ID here>

Hint: Set the variable only on production to turn off analytics for local development and non-production stages.