Search code examples
next.jsgoogle-analyticsanalyticsnext.js13

google analytics noindex issue nextjs


I've successfully added Google Analytics to my Next.js 13.5 project, and it's working well, showing me the pages users are visiting. However, I've encountered an issue where the <meta name="robots" content="noindex"/> tag is being added automatically. As a result, when I attempt to index my website, it doesn't seem to work as expected.

// GoogleAnalytics

import Script from "next/script";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { pageview } from "@/lib/gtagHelper";

export default function GoogleAnalytics() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const GA_MEASUREMENT_ID = `${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`;
  useEffect(() => {
    const url = pathname + searchParams.toString();

    pageview(GA_MEASUREMENT_ID, url);
  }, [pathname, searchParams, GA_MEASUREMENT_ID]);

  return (
    <>
      <Script
        async
        strategy="afterInteractive"
        src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`}
      />
      <Script
        async
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('consent', 'default', {
                    'analytics_storage': 'granted'
                });
                
                gtag('config', '${GA_MEASUREMENT_ID}', {
                    page_path: window.location.pathname,
                });
                `,
        }}
      />
    </>
  );
}

//Pageview

export const pageview = (GA_MEASUREMENT_ID: string, url: string) => {
  window.gtag("config", GA_MEASUREMENT_ID, {
    page_path: url,
  });
};

Solution

  • You can export metadata from your layout page with all metadata tags as objects using the Metadata Nextjs component.

    import type { Metadata } from 'next'
    
    
    export const metadata:Metadata = {
      robots: {
        index: true,
        googleBot: {
          index: true,
        },
      },
    };

    This will override the default generated meta tags from the NextJS server and have a lot of other customizations.