Update 2024: this solution still relevant.
In nextjs it could be a problem how the server and and client side code render and working together, it’s good to practice some of our nextjs, before we continue.
Solution
We’ll try to create a seperate compont that we can save in utility folder or somewhere else, and inside we’ll manage the complexicty of the google analytics code (in our case, or in some other case it could be any 3rd party javascript code):
const TrackingCode = () => {
return <>
<Script src="https://www.googletagmanager.com/gtag/js?id=G-1QVHEHLMVQ" />
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)}
gtag('js', new Date());
gtag('config', 'G-1QVHEHLMVQ');
`}
</Script>
</>
}
inside the head HTML tag of our nextjs application, we’ll inject the TrackingCode:
<head>
....
<TrackingCode/>
...
</head>
and it should work, and google analytics will be injected to the head HTML tag (you can check by inspecting your source code HTML in the browser).
Lior Amsalem embarked on his software engineering journey in the early 2000s, Diving into Pascal with a keen interest in creating, developing, and working on new technologies. Transitioning from his early teenage years as a freelancer, Lior dedicated countless hours to expanding his knowledge within the software engineering domain. He immersed himself in learning new development languages and technologies such as JavaScript, React, backend, frontend, devops, nextjs, nodejs, mongodb, mysql and all together end to end development, while also gaining insights into business development and idea implementation.
Through his blog, Lior aims to share his interests and entrepreneurial journey, driven by a desire for independence and freedom from traditional 9-5 work constraints.
Leave a Reply