How to Integrate Google AdSense Ads into Gatsby Sites

Gatsby uses React 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.

Depending on whether you choose to include Adsense ads on certain spots or whether you will leave this job to the Google AI, you can choose auto ads or custom ad blocks.

gatsby-ssr.js

const React = require('react')

const HeadComponents = [
  <script
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxx"
    crossOrigin="anonymous"
    async
    key="google-adsense-script"
  />
]

exports.onRenderBody = ({setHeadComponents}, pluginOptions) => {
  setHeadComponents(HeadComponents)
}

AdSense Component

import React, {useEffect} from 'react'
import styled from 'styled-components'

const Container = styled.div`
  display: flex;
  flex-direction: column;
  align-items: stretch;
  margin-bottom: 1rem;

  @media ${({theme}) => theme.media.mobile} {
    display: none;
  }
`

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

  return (
    <Container {...props}>
      <ins
        className="adsbygoogle"
        style={{display: 'block'}}
        data-ad-client="ca-pub-xxxxxxxxxxxxxxx"
        data-ad-slot="6568222285"
        data-ad-layout="in-article"
        data-ad-format="fluid"
      />
    </Container>
  )
}