Skip to content
DocsErrorsNext Script for Google Analytics

Next Script for Google Analytics

Prefer next/script component when using the inline script for Google Analytics.

Why This Error Occurred

An inline script was used for Google analytics which might impact your webpage's performance.

Possible Ways to Fix It

If you are using the gtag.js script to add analytics, use the next/script component with the right loading strategy to defer loading of the script until necessary.

pages/index.js
import Script from 'next/script'
 
function Home() {
  return (
    <div className="container">
      <Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" />
      <Script id="google-analytics">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());
 
          gtag('config', 'GA_MEASUREMENT_ID');
        `}
      </Script>
    </div>
  )
}
 
export default Home

Using analytics.js (legacy)

If you are using the analytics.js script to add analytics:

pages/index.js
import Script from 'next/script'
 
function Home() {
  return (
    <div className="container">
      <Script id="google-analytics">
        {`
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
 
          ga('create', 'UA-XXXXX-Y', 'auto');
          ga('send', 'pageview');
        `}
      </Script>
    </div>
  )
}
 
export default Home

If you are using the alternative async variant:

pages/index.js
import Script from 'next/script'
 
function Home() {
  return (
    <div className="container">
      <Script id="google-analytics">
        {`
          window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
          ga('create', 'UA-XXXXX-Y', 'auto');
          ga('send', 'pageview');
        `}
      </Script>
      <Script src="https://www.google-analytics.com/analytics.js" />
    </div>
  )
}
 
export default Home