How to add Adsense to a website built with GatsbyJS?

You can find here a nice tutorial on how to add Google AdSense in Gatsby.

Basically, the suggested way is to implement a Google AdSense Banner using React and including the Google AdSense code in the gatsby-ssr.js file.

gatsby-ssr.js file:

const React = require('react')

const HeadComponents = [
  <script
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXX"
    crossOrigin="anonymous"
    async
  />,
]

exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents(HeadComponents)
}

AdSense Banner component:

const Banner: React.FC<BannerProps> = ({
  className,
  style,
  layout,
  format,
  client = 'ca-pub-XXXX',
  slot,
  responsive,
  layoutKey,
}) => {
  useEffect(() => {
    try {
      const adsbygoogle = window.adsbygoogle || []
      adsbygoogle.push({})
    } catch (e) {
      console.error(e)
    }
  }, [])
  return (
    <div className={clx(container, className)}>
      <ins
        className="adsbygoogle"
        style={style}
        data-ad-layout={layout}
        data-ad-format={format}
        data-ad-client={client}
        data-ad-slot={slot}
        data-ad-layout-key={layoutKey}
        data-full-width-responsive={responsive}
      />
    </div>
  )
}

Don't use the gatsby-adsense plugin, it's deprecated.

Full article here.


if you are using services like Netlify to deploy your website, you can use snippet injection functionality to make this work without touching your source code.

settings -> build & deploy -> post processing -> snippet injection -> add snippet

then you can select where you want to add the snippet (script tag). For the Adsense this should be before the </head>. hope it helps. :)

enter image description here


Thanks to an answer given on Github, finally the problem is solved:

If you want to add Adsense:

  • cp .cache/default-html.js src/html.js
  • Add the script but everything inside should be escaped -> {<some-js-code-here>}
  • In my situation and as an example:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
             <script>
                  {`
                    (adsbygoogle = window.adsbygoogle || []).push({
                      google_ad_client: "ca-pub-1540853335472527",
                      enable_page_level_ads: true
                    });
                  `}
             </script>