You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14集成Google Analytics报错:window.gtag is not a function

问题:Next.js 14.0.4集成Google Analytics时window.gtag is not a function错误及Cookie consent问题

错误信息

window.gtag is not a function

背景情况

  • 基于Next.js 14.0.4集成Google Analytics,升级后出现该错误
  • 此前仅收集单一类型数据时可正常运行,现在需要收集多种数据
  • 已尝试的解决方案要么导致无法收集数据,要么Cookie consent无法正确设置
  • 已引入@types/gtag.js和client-only包

相关代码

layout.tsx

<html lang='en'>
    <head>
        <GoogleAnalytics />
    </head>
    <body className='overflow-x-hidden mx-auto w-[100vw] flex flex-col items-center justify-center box-border'>
        <Toaster />
        <Navbar />
        <div className="right-10 md:right-0 -top-10 md:top-10 absolute w-[100vw] h-[230px] gradient-02 -z-50 hidden sm:block" />
        <main className='w-[100vw] overflow-x-hidden mx-auto'>
            {children}
        </main>
        <Footer />
        <CookieBanner />
    </body>
</html>

CookieBanner组件代码

'use client';
/**
 * Type Definition
 */
type ConsentState = {
    adStorage: boolean
    analyticsStorage: boolean
}

export default function CookieBanner() {

    // Define useState
    const [cookieConsent, setCookieConsent] = useState<ConsentState>();

    // useEffect checks if cookie_consent is already set
    useEffect(() => {
        const storedCookieConsent = getLocalStorage("cookie_consent", null);
        setCookieConsent(storedCookieConsent);
    }, [setCookieConsent]);

    // useEffect updates once cookieConsent is updated to update the consent values
    useEffect(() => {
        const adStorage = cookieConsent?.adStorage ? 'granted' : 'denied'
        const analyticsStorage = cookieConsent?.analyticsStorage ? 'granted' : 'denied'

        // Check if window.gtag is there
        if (typeof window !== 'undefined' && typeof window.gtag !== 'undefined') {
            window.gtag("consent", 'update', {
                'analytics_storage': analyticsStorage,
                'ad_storage': adStorage,
            });
            console.log("Cookies set")
        } else {
            console.warn("gtag is not defined, cannot update consent.");
        }

        setLocalStorage("cookie_consent", cookieConsent);

    }, [cookieConsent]);


    return (
        <div
            className={`my-10 mx-auto max-w-[90%] md:max-w-screen-sm
                        fixed bottom-1 left-0 right-0 
                        ${cookieConsent != null ? "hidden" : "flex"} px-3 md:px-4 py-3 justify-between items-center flex-col gap-4 text-[17px]  
                        bg-[#2E3A59] rounded-lg shadow-white shadow z-50`}
        >
            <div className='flex flex-col sm:flex-row items-center justify-between gap-y-3 w-full'>
                <div className='text-center sm:text-left text-stone-200 w-fit min-w-[50%]'>
                    <Link href="/datapolicy" aria-label='Link to Data Policy'><p>This site uses <span className='font-bold text-primary hover:underline duration-1000'>Cookies.</span></p></Link>
                </div>
                <div className='flex gap-4 items-center justify-center w-full'>
                    <Button onClick={() => setCookieConsent({ adStorage: false, analyticsStorage: true })} size="md" variant="ghost" className='max-w-[33%] flex flex-col items-center justify-center' aria-label='Accept required Cookies'>
                        <span>Accept</span>
                        <span className='text-[11px]'>(required only)</span>
                    </Button>
                    <Button onClick={() => setCookieConsent({ adStorage: true, analyticsStorage: true })} size="md" variant="secondary" className='max-w-[60%]' aria-label='Accept all Cookies'>
                        Accept All
                    </Button>
                </div>
            </div>
        </div>
    )
};

已尝试操作

  • 调整layout中<GoogleAnalytics />组件的位置
  • 修改CookieBanner组件的逻辑

需求

解决window.gtag is not a function错误,确保Cookie consent正确设置,同时正常收集多种类型的Google Analytics数据。

内容的提问来源于stack exchange,提问作者Paul S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 01:32:35