Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use with new app router #596

Closed
devill opened this issue Oct 28, 2023 · 4 comments · Fixed by #642
Closed

How to use with new app router #596

devill opened this issue Oct 28, 2023 · 4 comments · Fixed by #642

Comments

@devill
Copy link

devill commented Oct 28, 2023

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?

@alekcarvalho
Copy link

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

@MauricioRobayo MauricioRobayo pinned this issue Nov 3, 2023
@shjacobs303
Copy link

shjacobs303 commented Nov 17, 2023

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.
  })
 // ...
}

@devill
Copy link
Author

devill commented Dec 4, 2023

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants