Search code examples
reactjsjsxadsensegatsbyhead

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?

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


Solution

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