17

I'd like to know where I should add the <script></script> provided by Google Adsense.

They say to add it into the <head></head>, but in Gatsby you have Helmet as <head>.

I tried also to add the script inside an html.js file where it's located a <head> tag with {``} to escape the <script> tag, but it outputs at the top of the website the script content.

TL;DR: What is the optimal way to add Adsense to a website built with GatsbyJS?

  • I've tried to use the react adsense package but I do not understand how to use it with Gatsby.
  • I have tried to add the <script> tag to html.js and it doesn't compile.
  • If you escape it with {``} you get the script as is, on top of the website.
<head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}
          {`<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> 
              `}
        </head>

source: html.js

The website should get detected by the Google crawlers.

Joe Doe
  • 433
  • 3
  • 7

5 Answers5

17

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

Sankha Karunasekara
  • 1,636
  • 18
  • 19
16

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>
Joe Doe
  • 433
  • 3
  • 7
  • Ultimately if you want to verify that Adsense has been added you can control if the ```` – Joe Doe Jan 21 '19 at 17:27
3

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.

  • 1
    Just a side note, for **Gatsby V2** (with ES6) you will need to use `export const onRenderBody` instead of `exports.onRenderBody`. – Ander Oct 19 '21 at 10:59
2

To set up Adsense, place the <script> tag (without template literals {``} just before your closing </body> tag in your html.js, like this:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
</body>

Then, to place an ad unit, you can either use a pre-built component like react-adsense on npm, as you mentioned, or build it yourself.

This is a useful article that covers both the setup and the placing of ad units with a component.

Let me know if this works for you or if something isn't clear!

Robin Métral
  • 3,099
  • 3
  • 17
  • 32
0

To add Google Adsence in Gatsby you need these three packages

react-adsense rehype-react gatsby-transformer-remark

and if you want to know how to implement these packages in your site then checkout this tutorial

Anshu Meena
  • 169
  • 1
  • 6