Closed Sribalaji-V-G closed 1 year ago
I was able to get it to work by using the package nextjs-google-analytics
.
// file: components/analytics/index.tsx
/* eslint-disable @typescript-eslint/no-explicit-any */
import Plausible from './Plausible';
import SimpleAnalytics from './SimpleAnalytics';
import Umami from './Umami';
import siteMetadata from '@/data/siteMetadata';
import { GoogleAnalytics } from 'nextjs-google-analytics';
declare global {
interface Window {
gtag?: (...args: any[]) => void;
plausible?: (...args: any[]) => void;
sa_event?: (...args: any[]) => void;
}
}
const isProduction = process.env.NODE_ENV === 'production';
const Analytics = () => {
return (
<>
{isProduction && (
<>
{siteMetadata.analytics.plausibleDataDomain && <Plausible />}
{siteMetadata.analytics.simpleAnalytics && <SimpleAnalytics />}
{siteMetadata.analytics.umamiWebsiteId && <Umami />}
{siteMetadata.analytics.googleAnalyticsId && (
<GoogleAnalytics
trackPageViews
gaMeasurementId={siteMetadata.analytics.googleAnalyticsId}
/>
)}
</>
)}
</>
);
};
export default Analytics;
I just checked and verified that the script works for GA4. Have you add https://*.googletagmanager.com
to the CSP as specified in https://developers.google.com/tag-platform/tag-manager/web/csp? Otherwise, it would be blocked.
Thanks guys it worked
Thank for your sharing, @PaulMest @timlrx!
Do you the have a javascript of your typescript code snippet? I'm facing an issue with the window object
Thanks
You can just remove the declare
block entirely. Everything else should work just fine.
// file: components/analytics/index.js
import Plausible from './Plausible';
import SimpleAnalytics from './SimpleAnalytics';
import Umami from './Umami';
import siteMetadata from '@/data/siteMetadata';
import { GoogleAnalytics } from 'nextjs-google-analytics';
const isProduction = process.env.NODE_ENV === 'production';
const Analytics = () => {
return (
<>
{isProduction && (
<>
{siteMetadata.analytics.plausibleDataDomain && <Plausible />}
{siteMetadata.analytics.simpleAnalytics && <SimpleAnalytics />}
{siteMetadata.analytics.umamiWebsiteId && <Umami />}
{siteMetadata.analytics.googleAnalyticsId && (
<GoogleAnalytics
trackPageViews
gaMeasurementId={siteMetadata.analytics.googleAnalyticsId}
/>
)}
</>
)}
</>
);
};
export default Analytics;
I'm using Google Analytics for the website using GA4 id starting with G-xxxxxxxx, but in my account it is not logging anything and Google Analytics not working. Can you solve this please?