1. Home
  2. Web Development
  3. Best way to add Google AdSense to Gatsby

Best way to add Google AdSense to Gatsby

Share

There are many ways to add Google AdSense to a website made with the Gatsby.JS generator, but it’s definitely hard to find the best one.

Advertising is essential especially for businesses like blogs, that offer their content for free. Writing unique and quality content takes a long time and, to make this cost sustainable, many blogs choose Advertising. For this reason, it is imperative that Ads loads properly, especially in a site that uses Gatsby as a generator. As you surely know, Gatsby uses React.js to route the navigation within the site, and this is not trivial especially when we want to implement an Advertising system such as Google AdSense, which has been mainly designed for Server-Side rather than Client-Side rendering.

In this article we will see the best way that I have personally found, right inside Polynique, to implement Google AdSense banners after lots of research and experiments.

Don’t use the Gatsby plugin for AdSense

Before we start, let me tell you something. This is mandatory: do not use the gatsby-plugin-google-adsense plugin, IT IS DEPRECATED. If this plugin worked, I wouldn’t be writing this article.

Does not work. That’s all. We can move on.

Add Google AdSense to Gatsby.js

The best way I found to add Google AdSense to Gatsby it’s the simplest one: just code it in your theme using React.js.

To add Google AdSense to Gatsby we need to:

Let’s now take a look at each step.

Add Google AdSense code in Gatsby-SSR.js file

The gatsby-ssr.js file lets you modify the static HTML while they are Server-Side Rendered. In this case, we will use the AdSense code provided by Google and include it into the <head> of our HTML pages.

To add the Google AdSense code in the <head> of every page with Gatsby.js we need to add the following code to the 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)
}

You will need to replace the “XXXX” with your publisher id, which you can find in your Google AdSense console.

Create a Google AdSense Banner component in React.js

Create a Banner component in React is pretty easy, you can choose to optimize the component depending on which type of banner you decided to include in your website. In my case, I’m using banners with “layout”, “format”, and “responsive” attributes, that’s why my component looks like this:

import React, { useEffect } from 'react'
import clx from 'classnames'
import { container } from './Banner.module.css'

interface BannerProps {
  className?: string
  style?: React.CSSProperties
  layout?: string
  format?: string
  client?: string
  responsive?: string
  slot: string
  layoutKey?: string
}

declare global {
  interface Window {
    adsbygoogle: any
  }
}

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>
  )
}

export default Banner

And the Banner.module.css is simply:

.container {
  margin-bottom: 1rem;
}

As you can see from the example below, I use declare global to make sure TypeScript doesn’t prompt me an error when trying to assign the adsbygoogle variable from the window. Also, I’m setting the client property with my Google AdSense publisher id as the default value.

To be sure that the component loads the banner, we are using the useEffect hook:

  useEffect(() => {
    try {
      const adsbygoogle = window.adsbygoogle || []
      adsbygoogle.push({})
    } catch (e) {
      console.error(e)
    }
  }, [])

This is an example of how I include the Banner component into my Gatsby.js pages:

<section className="...">
  <Banner
    className="adsbygoogle"
    style={{ display: 'block' }}
    slot="XXX"
    format="auto"
    responsive="true"
  />
  <article>
    ....
  </article>
</section>

Conclusion

In this article, we saw how to simply create a Google AdSense Banner component in React.js and how to include it in our Gatsby.js website. Also, we used the gatsby-ssr.js file to include the Google AdSense code to make AdSense work in the whole website.

If you like our post, please share it: