Implement a Google Analytics in a Qwik website
Implement a Google Analytics with Partytown in a Qwik website
Qwik is a new framework for building fast and interactive web applications. It uses a declarative and reactive approach to render components on demand, without any bundling or transpiling. Qwik also supports server-side rendering and progressive enhancement, making it ideal for SEO and performance.
One of the challenges of using Qwik is how to integrate third-party scripts, such as Google Analytics, into your website. Third-party scripts can slow down your initial page load and block the main thread, affecting the user experience and the core web vitals.
Fortunately, there is a solution: Partytown. Partytown is a library that helps relocate resource-intensive scripts into a web worker, and off of the main thread. By using Partytown, you can speed up your site by dedicating the main thread to your code, and offloading third-party scripts to a web worker.
In this article, we will show you how to use Partytown to add Google Analytics to your Qwik website, and how to solve the issue of the tag manager not rendering properly.
Prerequisites
To follow this tutorial, you will need:
- A Qwik project. You can use the Qwik starter or create your own.
- A Google Analytics account. You can sign up for free.
- Partytown dependency package.
Step 1: Install Partytown
The first step is to install Partytown in your Qwik project. You can do this easily by using the following Qwik starter script:
npm run qwik add partytown
The previous command updates your app and sets the correct configuration in vite.config.ts.
It also adds new files to your components folder.
Step 2: Add Partytown component to your root component
The next step is to add the Partytown component to your root component. This component will load the Partytown library and forward any data layer events to the web worker.
Open the src/root.tsx file and import the QwikPartytown component from the components/partytown/partytown module.
import { QwikPartytown } from './components/partytown/partytown';
Then, add the QwikPartytown component to the head element of your root component. You can pass an array of strings to the forward prop to specify which global variables or functions you want to forward to the web worker. In this case, we want to forward the dataLayer.push function, which is used by Google Analytics to send events.
export default component$(() => {
return (
<QwikCityProvider>
<head>
<meta charSet="utf-8" />
<QwikPartytown forward={['dataLayer.push']} />
...
</head>
<body lang="en"></body>
</QwikCityProvider>
);
});
Step 3: Add Google Analytics script to your root component
The next step is to add the Google Analytics script to your root component. This script will initialize the Google Analytics library and set your tracking ID.
However, instead of adding the script directly to the head element, we will use the type="text/partytown" attribute to tell Partytown to load the script in the web worker.
Also, instead of using the async attribute, we will use the defer attribute to defer the execution of the script until the document has been parsed.
Open the src/root.tsx file and add the following script element to the head element of your root component. Replace the G-XXXXXXX with your own Google Analytics tracking ID.
<script
defer
type="text/partytown"
src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"
/>
PS: Make sure that instead of directly calling google tag manager, use a proxy server to call it, and then use the proxy server URL in the src attribute of the script tag.
This is because Partytown does not support the use of third-party scripts directly, you can see it in this discord issue.
Step 4: Configure Google Analytics in your root component
The final step is to configure Google Analytics in your root component. This will enable the basic features of Google Analytics, such as page views and sessions.
However, instead of using the gtag function, which is not available in the web worker, we will use the dataLayer.push function, which we have forwarded to the web worker using the Partytown component.
Open the src/root.tsx file and add the following script element to the head element of your root component. Replace the G-XXXXXXX with your own Google Analytics tracking ID.
<script type="text/partytown">
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'G-XXXXXXX');
</script>
For SSG only, there is a solution for this issue at root.tsx
file, you can use the following code:
useOnWindow(
"load",
sync$(() => {
setTimeout(function () {
const gtmScript = document.createElement("script")
gtmScript.src = "https://www.googletagmanager.com/gtm.js?id=G-XXXXXXX"
gtmScript.async = true
document.head.appendChild(gtmScript)
}, 3000);
})
)
Step 5: Test your website
Now you are ready to test your website and see if Google Analytics is working properly.
To do this, you can run the following command to start your Qwik development server:
npm run dev
Then, open your browser and navigate to http://localhost:3000.
You should see your website rendered as usual, but without any noticeable performance impact from the Google Analytics script.
To verify that Google Analytics is receiving data from your website, you can open the Google Analytics dashboard and check the real-time reports.
You should see your page views and other metrics updated in real time.
Troubleshooting
If you encounter any issues with Partytown or Google Analytics, you can check the following tips:
Make sure you have installed Partytown correctly and updated your vite.config.ts file.
Make sure you have added the Partytown component and the Google Analytics scripts to your root component with the correct attributes and tracking ID.
Make sure you have forwarded the dataLayer.push function to the web worker using the Partytown component.
Make sure you have configured Google Analytics correctly using the dataLayer.push function in the web worker.
Check the browser console for any errors or warnings related to Partytown or Google Analytics.
Check the Partytown dashboard for any logs or events related to your website.
Check the Google Analytics dashboard for any data or reports related to your website.
Conclusion
In this article, we have shown you how to use Partytown to add Google Analytics to your Qwik website, and how to solve the issue of the tag manager not rendering properly.
By using Partytown, you can improve the performance and user experience of your website, while still benefiting from the features and insights of Google Analytics.
We hope you have enjoyed this article and learned something new. If you have any questions or feedback, please let us know in the comments below. Thank you for reading. 😊