1

Looking for a way to add Google Adsense without customizing html.js. I've tried proceeding with Helmet with:

<Helmet>
{process.env.GATSBY_GOOGLE_ADSENSE ? (
  <script
    data-ad-client={`${process.env.GATSBY_GOOGLE_ADSENSE}`}
    async
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
  ></script>
) : (
  console.log('Please add the env variable for Adsense')
)}
</Helmet>

but I run into the error:

AdSense head tag doesn't support data-react-helmet attribute.

Testing research after searching for resolution

gatsby-plugin-google-adsense

after install this throws an error that it isn't compatible with 3+ at time of writing this question, error message in terminal:

warn Plugin @isamrish/gatsby-plugin-google-adsense is not compatible with your gatsby version 3.0.1 - It requires gatsby@^2.13.50

Add to Netlify

Searching the site I found this Q&A that suggested to add during post processing but if I'm not using Netlify that really doesn't provide a solution.

Modify html.js

This answer is an option if I were building before pushing source to the repository but I am not.

Not able to connect AdSense to Gatsby blog

  1. suggests the plugin I mentioned that throws an error in 3+
  2. suggests add to html.js

At time of writing I'm unable to find a solution for Gatsby 3+. In Gatsby how can I add google-adsense to gatsby-ssr.js so that I can get adsense to work?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127

1 Answers1

0

I'm not sure if it will work for your use-case but here are some trials:

  • Use gatsby-plugin-react-head which extends from react-head but you may face the same incompatibility with data-react-helmet attribute.

  • Use the gatsby-ssr.js API: onRenderBody, which exposes a setHeadComponents props:

    export const onRenderBody = ({ setHeadComponents }) =>
      setHeadComponents([
        <script data-ad-client={`${process.env.GATSBY_GOOGLE_ADSENSE}`} async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"/>
    ]);
    
    

    Note the ES6 naming

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67