Add Google AdSense to Gatsby site

November 05, 2021

programming
article cover

Google AdSense + Gatsby

Google AdSense is a super useful service to display ads on your site just by adding <script> tag. But with Gatsby which is SSG, we need to do some tricks to display ads on your website.

Requirement

I assume you already signed up for Google AdSense and knew your client ID.

2 ways to do

1. Use Gatsby Server Rendering APIs

The first way is using setHeadComponents of Gatsby Server Rendering APIs. That allows us to insert Google AdSense script tag inside <head> during SSR build.

If you intend to display only auto ads, this is enough. The rest of the work should be done on Google AdSense.

*Do not forget to add your client ID as a query.

// gatsby-ssr.js

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      async
      src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=<YOUR CLIENT ID>" 
      crossOrigin="anonymous"
    ></script>
  ])
} 

2. Use a plugin

The second way is using a plugin as always we do with Gatsby. But there is one note to use a plugin.

when googling like “gatsby google adsense”, you would come across the following plugin

gatsby-plugin-google-adsense

And many people seem using this plugin but this is no longer maintained. It doesn’t work well in most cases. I actually tried this plugin first but met weird behaviour then.

This↓ is the one we should use.

@isamrish/gatsby-plugin-google-adsense

Install it and edit gatsby-config.js as we always do.

npm install --save @isamrish/gatsby-plugin-google-adsense

or

yarn add @isamrish/gatsby-plugin-google-adsense
// gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `@isamrish/gatsby-plugin-google-adsense`,
      options: {
        googleAdClientId: "<YOUR_GOOGLE_ADSENSE_ID>",
        head: false // Optional
      }
    }
  ]
};

Again, if you intend to display only auto ads, this is enough. Done.

Make component for AdSense

Auto Ads is not all we can do with Google AdSense, of course. You can insert ads with different sizes at the preferable place.

// src/components/googleAdsense.js

import React, { useEffect } from 'react'

export const Adsense = ({ path }) => {
  useEffect(() => {
    ;(window.adsbygoogle = window.adsbygoogle || []).push({})
  }, [path])
  
  return (
    <ins 
      className="adsbygoogle"
      style={{ "display": "block" , textAlign: "center"  }}
      data-ad-client="<YOUR_GOOGLE_AD_CLIENT_ID>"
      data-ad-slot="<YOUR_GOOGLE_AD_SLOT>"
      data-ad-format="auto"
      data-full-width-responsive="true"
    />
  )
}

Don’t forget to put your Client ID and Slot number you get from Google AdSense on data-ad-client and data-ad-slot respectively. The thing done inside useEffect is the key. Without it, ads wouldn’t show up correctly.

It’s not mandatory but passing path to the component is a good way to make the component re-render and show a new ad every time the page changes.

Then import it and use it anywhere you like.

// sample.js
import React from 'react'
import { Adsense } from './googleAdsense'

export const SampleCompo = (props) => {
  const path = props.location?.pathname || ''
  
  return (
    <div>
      <Adsense path={path} />
    </div>
  )
}

Profile picture

Photographer / Web engineer working in Berlin.
A Japanese living with a Slovak wife and two German cats.