Search code examples
google-analyticslighthousesamesite

Google Analytics Cross-Site Cookie Issues


Including Google Analytics on our site drops the LightHouse Best Practices score 7% because of Errors in the Issues Tab. Looking at the Issues Tab shows that Google Analytics is sending 6 cookies without the necessary SameSite value set. Is there any way to fix/address this?

same site cookies issue

before google analytics

after google analytics


Solution

  • Found leads to the Solution buried deep in the Google developer docs here: https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id

    With a little tweaking of my own I came up with this solution:

    const gacode = 'UA-XXXXX-Y';
    const rootdomain = 'example.com';
    const GA_LOCAL_STORAGE_KEY = 'ga:clientId';
    const GA_COOKIE_KEY = 'gaCookie';
    if (window.localStorage) {
        ga('create', gacode, {
            storage: 'none',
            clientId: window.localStorage.getItem(GA_LOCAL_STORAGE_KEY),
        });
        ga(function (tracker) {
            window.localStorage.setItem(
                GA_LOCAL_STORAGE_KEY,
                tracker.get('clientId')
            );
        });
    } else {
        ga('create', gacode, {
            cookieName: GA_COOKIE_KEY,
            cookieDomain: rootdomain,
            cookieExpires: 60 * 60 * 24 * 28,
            cookieUpdate: 'false',
            cookieFlags: 'SameSite=None; Secure',
        });
    };
    

    This uses analytics in a cookieless mode via localstorage if available and if not adds the SameSite flags to the cookies. This probably isn't the default because it limits cross site tracking.

    It still drops performance by one point even with all the tricks like prefetching the dns and preloading the analytics script, because their script tags in a second script dynamically, but much better. No more dings for Bad Practices in the Issues Tab at least.

    <link rel="dns-prefetch" href="https://www.google-analytics.com" />
    <link
        rel="preload"
        href="https://www.google-analytics.com/analytics.js"
        as="script"
    />
    

    and including the script async

    <script async src="https://www.google-analytics.com/analytics.js"></script>
    

    This gets us most of the way back.

    enter image description here

    Hope this answer is as helpful to someone else as it was to me.