Joe Doe
Joe Doe

Reputation: 443

How to add Adsense to a website built with GatsbyJS?

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?

<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.

Upvotes: 17

Views: 6836

Answers (5)

Anshu Meena
Anshu Meena

Reputation: 381

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

Upvotes: 0

Domenico Ruggiano
Domenico Ruggiano

Reputation: 587

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.

Upvotes: 4

Sankha Karunasekara
Sankha Karunasekara

Reputation: 1726

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

Upvotes: 18

Joe Doe
Joe Doe

Reputation: 443

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>

Upvotes: 17

Robin M&#233;tral
Robin M&#233;tral

Reputation: 3209

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!

Upvotes: 2

Related Questions