MauricioRobayo/nextjs-google-analytics

How to use with new app router

devill opened this issue · 4 comments

I can't find documentation on how this can be used with the new app router of next.js 13. Can someone please help me?

You can follow these steps:

  1. Put the GA ID in your .env:
    NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"

  2. Create a component and paste the regular code (e.g. GAnalytics.tsx):

"use client";

import { GoogleAnalytics } from "nextjs-google-analytics";

const GAnalytics = () => {
  return <GoogleAnalytics trackPageViews />;
};

export { GAnalytics };
  1. Then import your component into your app/layout.tsx
import { GAnalytics } from "@/components/GAnalytics";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={font.className}>
        <GAnalytics />
        {children}
      </body>
    </html>
  );
}
  1. Done

The above worked for me, I had to convert to the new metadata import for page views to work.

However web vitals aren't sending anymore. I've tried adding the documented approach to the client component in various ways but it doesn't run or send the event to GA.

Has anyone got this working using app router?

import { event } from 'nextjs-google-analytics'
import type { NextWebVitalsMetric } from 'next/app'

export function ReportWebVitals(metric: NextWebVitalsMetric): void {
  const { name, label, value, id } = metric
  console.log('event run')
  event(name, {
    category: label === 'web-vital' ? 'Web Vitals' : 'Next.js custom metric',
    value: Math.round(name === 'CLS' ? value * 1000 : value), // values must be integers
    label: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate.
  })
 // ...
}

Thank you!