谷歌分析noindex issue nextjs

2mbi3lxu  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(134)

我已经成功地将Google Analytics添加到我的Next.js 13.5项目中,并且它运行良好,向我显示用户正在访问的页面。然而,我遇到了一个自动添加<meta name="robots" content="noindex"/>标签的问题。因此,当我尝试索引我的网站时,它似乎无法按预期工作。
// 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,
                });
                `,
        }}
      />
    </>
  );
}

字符串
//页面视图

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

a14dhokn

a14dhokn1#

您可以使用Metadata Nextjs组件将所有元数据标记作为对象从布局页面导出元数据。

import type { Metadata } from 'next'

export const metadata:Metadata = {
  robots: {
    index: true,
    googleBot: {
      index: true,
    },
  },
};

字符串
这将覆盖NextJS服务器默认生成的Meta标记,并有很多其他自定义。

相关问题