javascriptnext.jsgoogle-analytics

How to fix CORS error from Google Analytics in Next.Js 13?


I am using a common pattern for Google Analytics in Next.JS:

export function AnalyticsProvider({ children }) {
  const gaMeasurementId = 'MY GA ID HERE';
  const reportDomain = 'https://www.google-analytics.com';

  return (
    <>
      {children}
      <Script
        id="google-analytics-js-cdn"
        src={`https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}`}
        strategy="afterInteractive"
      />
      <Script
        id="google-analytics"
        strategy="afterInteractive"
        dangerouslySetInnerHTML={{
          __html: `
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
            
              gtag('config', '${gaMeasurementId}', {
                 page_path: window.location.pathname,
                 transport_url: '${reportDomain}',
                 first_party_collection: true
              });
          `,
        }}
      />
    </>
  );
}

When the second script executes I am getting the following error in the console:

Access to XMLHttpRequest at 'https://www.google-analytics.com/g/collect?v=2& ... <SNIP />' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Which seems a bit confusing because that request is a GET request. Has anyone encountered this?


Solution

  • I know I arrived 1 year late but you can use Google Analytics with Next.js 14, more info here https://nextjs.org/docs/messages/next-script-for-ga