DEV Community

Ludivine A
Ludivine A

Posted on • Updated on

How to add ads to your GatsbyJS blog

If you wish to learn how to add ads to your Gatsby blog, this article is made for you !

I am going to teach you how to add Google Adsense and possibly earn money !

Auto Ads

Auto Ads are ads that Google will automatically position on your website, based on algorithms.

To activate them, go on your website ad settings and check the option "Automatic ads"

Installation of the plugin on Gatsby

/!\ This plugin has been deprecated. Other plugins with similar names are available but I didn't test them, as I do not recommend using Auto Ads.

// NPM
npm install --save gatsby-plugin-google-adsense

// Yarn
yarn add gatsby-plugin-google-adsense
Enter fullscreen mode Exit fullscreen mode

Add the plugin on Gatsby

First you will need to get your Publisher ID from Google Adsense to link your website to Google. To find it, click on "Account" and copy your Publisher ID.

Then, in your gatsby-config.js ad this bit of code with your Publisher ID.

plugins: [
    resolve: `gatsby-plugin-google-adsense`,
    options: {
      publisherId: `PUBLISHER ID`,
Enter fullscreen mode Exit fullscreen mode

But I would not recommend using Auto Ads, as Google tends to add to many of them, and in odd places. The user experience on your website will majorly decrease.

Manual ad block are, I believe, a better solution.

Create ad units

You can create ad units, that you can integrate in specific places manually. To create them, click on "Ads", then click on "By ad units" and select "Display ads".

You can change its shape and make it be a square, horizontal or vertical.

Install react-adsense

To integrate these ads to you blog, you need to install react-adsense.

// NPM
npm install --save react-adsense

// Yarn
yarn add react-adsense
Enter fullscreen mode Exit fullscreen mode

Integrating ads to the blog

This library offers components that you can use to display ads. You will need your Publisher ID and the id of your ad that you can find under the unit's name.

// The minimum set up to make it work.
  client='PUBLISHER ID'
  slot='UNIT ID'

// All possible options.
Enter fullscreen mode Exit fullscreen mode

Complying with the rules

In the Privacy & messaging tab, you will be able to add a GDPR or a CCPA message to comply with user consent rules.

Preventing certain ads

In the Blocking controls tab, you can select the themes of ads that can appear on your website. I would suggest block certain ads such as the more "sulfurous" ones if you know what I mean. It's not very professional 😉.

Now you know how to put ads on your GatsbyJS blog ! Don't hesitate to ask questions !

Originally posted on my blog. Check out my instagram account to learn more about web development.

Top comments (0)