Error: dataLayer is not defined

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).

Leave a Reply

Your email address will not be published. Required fields are marked *

All rights reserved 2024 ©