How to run Google Analytics in Next JS without crippling the performance?

193 Views Asked by At

I finished building a Next JS website and as a finishing touch, I added Google Analytics.

But when I added Google Analytics my page performance dropped from 96 to 78.

TBT jumps from 210ms to 810ms, and sometimes the LCP and SI also suffer.

After researching how to fix my performance issue I found the Partytown Library

I tried to use the Partytown Library to send the Google Analytics script to a web worker, but I can't figure out how it works.

This is how I tried to use the Partytown library:

import Header from "@/components/universal/Heder/Header";
import "./globals.css";
import StyledComponentsRegistry from "../lib/registry";
import Footer from "@/components/universal/Footer/Footer";
import ScrollToTopButton from "@/components/universal/ScrollButton/ScrollToTopButton";
export const metadata = {
    title: "Visit Drežnica | Rent a Room",
    description:
        "Drežnica near Mostart. Experience serene mountains, a picturesque river, and warm hospitality. Perfect for nature lovers seeking a peaceful getaway.",
};
import Head from "next/head";
import { Partytown } from "@builder.io/partytown";

export default function RootLayout({ children }) {
    return (
        <html lang="en" suppressHydrationWarning={true}>
            <StyledComponentsRegistry>
                <Head>
                    <title>My App</title>
                    <Partytown debug={true} forward={["dataLayer.push"]} />
                    <script
                        src="https://www.googletagmanager.com/gtag/js?id=###########"
                        type="text/partytown"
                        async
                    />
                    <script type="text/partytown">
                        {`
                        window.dataLayer = window.dataLayer || [];
                        function gtag(){dataLayer.push(arguments);}
                        gtag('js', new Date());
                        gtag('config', '###########');
                    `}
                    </script>
                </Head>
                <body suppressHydrationWarning={true}>
                    <header>
                        <Header />
                    </header>
                    {children}
                    <ScrollToTopButton />
                    <footer>
                        <Footer />
                    </footer>
                </body>
            </StyledComponentsRegistry>
        </html>
    );
}

This is my nextjs.config:

/** @type {import('next').NextConfig} */
const nextConfig = {
    compiler: {
        styledComponents: true,
    },
    experimental: {
        nextScriptWorkers: true,
    },
};

export default nextConfig;

This is just one of the ways I tried to use the Partytown Library, I tried a bunch but I couldn't figure out how it works.

I tried for 4 days straight to find a solution but didn't find anything useful.

Let me know if you have any clue on how to set up Partytown or use Google Analytics.

1

There are 1 best solutions below

1
Sean W On

Next.js has optimized a couple of Google packages like Tag Manager and Analytics to solve issues similar to yours via the @next/third-parties package.

You can see the official Next.js implementation docs

Analytics - root layout.tsx

import { GoogleAnalytics } from '@next/third-parties/google'
     
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-XYZ" />
    </html>
   )
}

Tag manager - root layout.tsx

import { GoogleTagManager } from '@next/third-parties/google'
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleTagManager gtmId="GTM-XYZ" />
    </html>
  )
}