Hi there,
I have been using google analytics4/gtm for the past year and it was working ok, the performance was a real issue on mobile devices, and thought there wasn’t much i could do about it until today when i discovered Partytown which is interesting.
I have implemented Partytown and is working with the standard ‘page_view’ event, but all my other custom events are not being triggered in the network tab and thus not sent to Google.
_document.tsx:
import { Partytown } from '@builder.io/partytown/react';
export default function Document() {
return (
<Html>
<Head>
<Partytown debug={true} forward={['dataLayer.push']} />
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script
type="text/partytown"
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`}
/>
<script
type="text/partytown"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}');`,
}}
/>
{/* END Global Site Tag (gtag.js) - Google Analytics */}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
lib/ga/index.tsx (custom events)
export const pageview = (url) => {
window.dataLayer.push({
event: 'pageview',
page_path: url,
});
};
export const pageEvent = ({ action, params }) => {
window.dataLayer.push({
event: action,
...params,
});
};
export const click = ({ action, params }) => {
window.dataLayer.push({
event: action,
...params,
});
};
export const searchBarEvent = ({ action, params }) => {
window.dataLayer.push({
event: action,
...params,
});
};
export const equipmentFilterSelectionEvent = ({ action, params }) => {
window.dataLayer.push({
event: action,
...params,
});
};
An example of a custom event trigger:
useEffect(() => {
if (category) {
const brandNames = Object.values(brands).map((brand) => brand.title);
pageEvent({
action: 'category_page',
params: {
category_page: category.slug,
category_brands: brandNames,
categories_views: 1,
},
});
}
}, [category]);
VS studio is alerting that ‘dataLayer’ : Property ‘dataLayer’ does not exist on type ‘Window & typeof globalThis’.
i also have this in the console whenever i refresh a page that is supposed to fire a custom event:
-A bad HTTP response code (404) was received when fetching the script.
TypeError: Failed to register a ServiceWorker for scope (‘http://localhost:3001/~partytown/debug/’) with script (‘http://localhost:3001/~partytown/debug/partytown-sw.js’):
-A bad HTTP response code (404) was received when fetching the script.
Promise.then (async)
u @ wheel-loaders:2
cf12cdfc-eb79-449c-ac23-af2d4bc4644a:2
-Fetch finished loading: GET “https://www.googletagmanager.com/gtag/js?id=G-B3CQW559BB”.
Thanks in advance for taking the time to read and trying to help me solve this issue.